Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "<<" exactly do in ruby?

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?

like image 853
KZcoding Avatar asked Nov 27 '22 11:11

KZcoding


2 Answers

The << operator is adding items to the result array in this case.

See " how to add elements to ruby array (solved)".

like image 86
Bassam Mehanni Avatar answered Jan 22 '23 19:01

Bassam Mehanni


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.

like image 22
Alex D Avatar answered Jan 22 '23 21:01

Alex D