So this is legal in Ruby:
puts key: "value"
{:key=>"value"}
But this is not:
hsh = key: "value"
puts hsh
sandbox.rb:1: syntax error, unexpected ':', expecting end-of-input
hsh = key: "value"
Why not? When am I allowed to omit curly braces for hashes?
You can omit braces when a hash is the last argument of a method call. When you write:
puts key: 'value'
you actually call the puts method with a param of {key: value}, so you can write:
puts({key: 'value'})
but in Ruby you can skip both normal and curly braces.
To see how it works in detail, consider these examples:
# Hash as only paramter
puts(a:1)
#{:a=>1}
# Hash as a last parameter
puts('cat', a: 1)
#cat
#{:a=>1}
# Hash as a first parameter - cannot skip
puts(a: 1, 'cat')
# >> SyntaxError: unexpected ')', expecting =>
# >> puts(a: 1, 'cat')
^
puts({a: 1}, 'cat')
#{:a=>1}
#cat
# Two hashes
puts({a: 1}, {b: 2})
#{:a=>1}
#{:b=>2}
puts({a: 1}, b: 2)
#{:a=>1}
#{:b=>2}
You can omit the braces when a hash is the last argument being passed to a function. So, you don't need them for options in a Rails link_to helper, for example, but you do need them in your hsh = key: "value" example because there's no function for the hash to be an argument of.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With