I am learning Ruby through RubyMonk. In solving the problem of a robot waiter, there is a line of code that creates a new hash using an array:
o = Hash[*order]
given
order = [:table, 1, :sandwich, "denver", :drink, "mango shake"]
I understand what is being done here and how the splat operator works. However, I am confused by the syntax for creating this hash. RubyDoc says that ::[] is really a callable method, so I was able to determine that o = Hash::[](*order) is the same. But why can this be reduced to just Hash[*order] ? Is this a special construct that is interpreted by the parser, or is there another reason? Along the same lines, why not one of the following works?
o = Hash.new o.[](*order)
or
o = Hash.new o[*order]
or even something like o = {}[*order]
I know this should not work; I just donβt know why. I think it bothers me to use Hash[*order] without the first hash instance with Hash.new . Is this an example of the difference between class methods and instance methods?
(As a note, it seems to me that o = {*order} should work, but it is not.)
Can someone explain what is happening here and are there alternative ways to add values ββfrom an array to a hash?
source share