I’m learning the basics of Ruby (just starting out), and I came across the Hash.[] method. It was introduced with
a = ["foo", 1, "bar", 2]
=> ["foo", 1, "bar", 2]
Hash[*a]
=> {"foo"=>1, "bar"=>2}
With a little thought, I figured out that Hash[*a] is equivalent to Hash.[](*a) or Hash.[] *a. My question is why that’s the case. What is it that lets you put the *a inside the square brackets, and is there some kind of rule for where and when else “it” can be used?
Edit: My wording seems to be causing some confusion. I’m not asking about the array expansion. I get that. My question is basically: if [] is a method name, why is it okay to put arguments inside the brackets? It seems almost–but not quite–like saying that if you have a method Foo.dood, and you wanted to pass the string "hey" to it, then you could write Foo.do"hey"od.
There are a couple methods that ruby lets you call in a special way. These are the
[]as you mentioned, the+,-,==and the like as someone else mentioned. Another important example are methods of the formsomething=(value)which can be called withobject.something = valueand allow you to create accessors.Edit:
Fun fact 1: if you define a
+method you get+=for free.Fun fact 2: if you define a
<=>you get all comparison methods, courtesy of Comparable