Need to refactor to the new Ruby 1.9 hash syntax [duplicate]

风格不统一 提交于 2019-12-05 08:15:39

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' }

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' }

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 }

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 }

So you can try with:

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

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
service 'apache' do
  supports status: true, restart: true, reload: true
end

You can use this new syntax when you have symbols as keys.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!