Ruby - Difference between Array#<< and Array#push

RavensKrag picture RavensKrag · May 13, 2012 · Viewed 30.5k times · Source

From examining the documentation for Ruby 1.9.3, both Array#<< and Array#push were designed to implement appending an element to the end of the current array. However, there seem to be subtle differences between the two.

The one I have encountered is that the * operator can be used to append the contents of an entire other array to the current one, but only with #push.

a = [1,2,3]
b = [4,5,6]

a.push *b
=> [1,2,3,4,5,6]

Attempting to use #<< instead gives various errors, depending on whether it's used with the dot operator and/or parentheses.

Why does #<< not work the same way #push does? Is one not actually an alias for the other?

Answer

x1a4 picture x1a4 · May 13, 2012

They are very similar, but not identical.

<< accepts a single argument, and pushes it onto the end of the array.

push, on the other hand, accepts one or more arguments, pushing them all onto the end.

The fact that << only accepts a single object is why you're seeing the error.