tags:

views:

240

answers:

2

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?

+11  A: 

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.

workmad3
+1  A: 

This seems like a good place to mention another alternate syntax, using the comma to separate items within braces (using your example):

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

I don't normally use the comma syntax in standard code -- like workmad3 says, the arrow (=>) makes the hash more obvious. But in an interactive Ruby session (irb), it is easier to type a comma than the arrow:

{:eyes, "blue", :height, 6.2}  # => {:height=>6.2, :eyes=>"blue"}
slothbear