需要重构为新的Ruby 1.9哈希语法 [英] Need to refactor to the new Ruby 1.9 hash syntax
问题描述
我有一个食谱,其中包含以下代码,该代码无法通过棉绒测试:
I have a recipe that has the following code that is failing a lint test:
service 'apache' do
supports :status => true, :restart => true, :reload => true
end
失败,并显示以下错误:
It fails with the error:
Use the new Ruby 1.9 hash syntax.
supports :status => true, :restart => true, :reload => true
不确定新语法是什么样的...任何人都可以提供帮助吗?
Not sure what the new syntax looks like... can anyone please assist?
推荐答案
在Ruby 1.9版中,为键为符号的哈希文字引入了新的语法.哈希使用哈希火箭"运算符来分隔键和值:
In the Ruby version 1.9 has been introduced a new syntax for hash literals whose keys are symbols. Hashes use the "hash rocket" operator to separate the key and the value:
a_hash = { :a_key => 'a_value' }
在Ruby 1.9中,此语法有效,但是只要键是符号,也可以将其写为:
In Ruby 1.9 this syntax is valid, but whenever the key is a symbol it's also possible to write it as:
a_hash = { a_key: 'a_value' }
正如Ruby样式指南所述,当您的哈希键是符号时,您应该更喜欢使用Ruby 1.9哈希文字语法
And as the Ruby style guide says, you should prefer to use the Ruby 1.9 hash literal syntax when your hash keys are symbols (see):
# bad
hash = { :one => 1, :two => 2, :three => 3 }
# good
hash = { one: 1, two: 2, three: 3 }
还有一个附加提示:不要在同一哈希文字中将Ruby 1.9哈希语法与哈希火箭混合使用.当您拥有不是符号的键时,请遵循哈希火箭的语法(请参阅):
And as an additional hint: Don't mix the Ruby 1.9 hash syntax with hash rockets in the same hash literal. When you've got keys that are not symbols stick to the hash rockets syntax (see):
# bad
{ a: 1, 'b' => 2 }
# good
{ :a => 1, 'b' => 2 }
因此您可以尝试:
service 'apache' do
supports status: true, restart: true, reload: true
end
如果要查看Rubocop的方法",可以在命令行中运行它,这将仅针对HashSyntax
警告或标志自动校正代码:
If you want to see what's the Rubocop "way" you can run this in the command line, this will autocorrect your code only for the HashSyntax
warnings or flags:
rubocop --only HashSyntax --auto-correct
这篇关于需要重构为新的Ruby 1.9哈希语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!