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

2

18

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?

Eisler answered 16/5, 2017 at 15:17 Comment(0)
T
33

A new syntax for hash literals whose keys are symbols was introduced in Ruby 1.9. Hashes commonly 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):

# non-recommended
hash = { :one => 1, :two => 2, :three => 3 }

# recommended
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):

# non-recommended
{ a: 1, 'b' => 2 }

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

So you could 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
Tremaine answered 16/5, 2017 at 15:18 Comment(2)
How would I type a hash with 2 symbols, like: {:key => :value, :key2 => :value2} ?Prevention
Just { key: :value, key2: :value2 }, both values, hash key and hash value are symbols.Orangeism
C
0
service 'apache' do
  supports status: true, restart: true, reload: true
end

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

Campy answered 16/5, 2017 at 15:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.