需要重构为新的 Ruby 1.9 哈希语法

Need to refactor to the new Ruby 1.9 hash syntax

我有一个食谱,其中包含以下未通过 lint 测试的代码:

service 'apache' do
  supports :status => true, :restart => true, :reload => true
end

失败并出现错误:

Use the new Ruby 1.9 hash syntax.
  supports :status => true, :restart => true, :reload => true

不确定新语法是什么样的...有人可以帮忙吗?

service 'apache' do
  supports status: true, restart: true, reload: true
end

当您将符号作为键时,您可以使用这种新语法。

在 Ruby 版本 1.9 中引入了一种新的哈希文字语法,其键是符号。哈希使用 "hash rocket" 运算符来分隔键和值:

a_hash = { :a_key => 'a_value' }

在 Ruby 1.9 中,此语法有效,但只要键是符号,也可以将其写为:

a_hash = { a_key: 'a_value' }

正如 Ruby 风格指南所说,当您的散列键是符号 (see):

时,您应该更喜欢使用 Ruby 1.9 散列文字语法
# bad
hash = { :one => 1, :two => 2, :three => 3 }

# good
hash = { one: 1, two: 2, three: 3 }

另外一个提示:不要在同一个哈希文字中混合使用 Ruby 1.9 哈希语法和哈希火箭。当您获得不是符号的键时,请遵循哈希火箭语法 (see):

# bad
{ a: 1, 'b' => 2 }

# good
{ :a => 1, 'b' => 2 }

所以你可以试试:

service 'apache' do
  supports status: true, restart: true, reload: true
end

如果您想查看什么是 Rubocop "way",您可以在命令行中 运行 这样做,这将仅针对 HashSyntax 警告或标志自动更正您的代码:

rubocop --only HashSyntax --auto-correct