I am learning the basics of Ruby (just getting started) and I came across a method Hash.[]. It was introduced using
a = ["foo", 1, "bar", 2]
=> ["foo", 1, "bar", 2]
Hash[*a]
=> {"foo"=>1, "bar"=>2}
After a little thought, I realized that it is Hash[*a]equivalent to Hash.[](*a)or Hash.[] *a. My question is why this is the case. What allows you to put *ain square brackets, and is there any rule for where and when you can still use it?
Edit: My wording causes some confusion. I am not asking about array expansion. I understand. My question is basically: if []is the name of the method, why is everything okay to put arguments inside the brackets? It seems almost, but not quite, for example, saying that if you have a method Foo.doodand you wanted to pass a string to it "hey", then you could write Foo.do"hey"od.
source
share