I am new to Ruby, so I am still learning several things. But, I do have good experience with Java and C.
I would like to know what this does exactly:
[ 'a','b', 'c' ].each_with_index {|item, index| result << [item, index] }
Specifically, I am interested in the <<
. Some research tells me that it is used for bit shifting, but it's obvious that is not the case here, so what is it doing here?
The <<
operator is adding items to the result array in this case.
See " how to add elements to ruby array (solved)".
In Ruby, all the things which are operators in C/Java, like +, -, *, /, and so on, are actually method calls. You can redefine them as desired.
class MyInteger
def +(other)
42 # or anything you want
end
end
Array defines the <<
method to mean "push this item on the end of this array". For integers, it's defined to do a bit shift.
Aside from Array, many other classes define <<
to represent some kind of "appending" operation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With