Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bracket syntax for Ruby Hashes

Tags:

syntax

ruby

hash

Do these two statements pass the same type of argument (a Hash) to the new method?

@seat = Seat.new(:flight_id => @flight.id)

@seat = Seat.new({:flight_id => @flight.id})

Do the Hash brackets {} change anything in the second example?

like image 930
eggdrop Avatar asked Sep 26 '26 11:09

eggdrop


1 Answers

They are both the same, the {} add nothing in the second argument, apart from making things even more explicit than they already were (using the => syntax is enough to say 'this is a hash' to anyone using ruby for any length of time).

Ruby will automatically turn a list of parameters like:

someFunction(:arg1 => value1, :arg2 => value2)

into a hash and pass it as a single argument for you. The time when you need to add {} around hashes is when you have things like a hash of hashes or a function that expects two hashes (such as several rails methods when you need to pass both options and html_options), like this:

someFunction({:arg1 => value1, :arg2 => value2}, {:arg3 => value3})

which will pass in two hashes (the interpreter wouldn't be able to deduce where the 2 hashes were split if left to itself, so you need to give it the {} to tell it what to do in this case)

More information is available in the Pickaxe book chapter: More About Methods in the section on Collecting Hash Arguments at the bottom.

like image 112
workmad3 Avatar answered Sep 28 '26 01:09

workmad3