Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When can I omit curly braces for a Ruby hash?

Tags:

ruby

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?

like image 335
Kenny Worden Avatar asked Nov 04 '25 22:11

Kenny Worden


2 Answers

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}
like image 86
mrzasa Avatar answered Nov 07 '25 10:11

mrzasa


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.

like image 27
JohnP Avatar answered Nov 07 '25 08:11

JohnP



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!