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

 ̄綄美尐妖づ 提交于 2019-12-07 04:11:26

问题


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?


回答1:


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



回答2:


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

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



来源:https://stackoverflow.com/questions/44005410/need-to-refactor-to-the-new-ruby-1-9-hash-syntax

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