B.2 Curly braces around hash arguments
Consider a hypothetical method that accepts a Hash as its last argument:
some_method("first_argument", 2, { :this => "argument", :is => "a Hash" })How many arguments does the above method have? You might be tempted to say four or even six if you just count, but really it’s three: a string is first, an integer is second, and the entire hash ({ :this => "argument", :is => "a Hash" }) is the third and final argument.
In the case that a Hash literal is being used as the last argument to a method, you can optionally drop the curly braces around it:
some_method("first_argument", 2, :this => "argument", :is => "a Hash")Now it really looks like the method is taking more than three arguments, but it’s not; Ruby can figure out from the hash rockets that the stuff at the end is really just one Hash.
Note that you can only drop the curly braces around a Hash in this one, very specific case — if the Hash is the last argument to a method. So this:
# Creating a Hash literal and storing it in a variable:
my_hash = { :fruit => "banana", :sport => "hockey" }is not the same as this:
# The below is nonsensical, as far as Ruby is concerned:
my_hash = :fruit => "banana", :sport => "hockey"
# You can't drop the curly braces around the Hash unless it is the last argument to a method.