64

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?

Christopher Oezbek
  • 20,679
  • 5
  • 53
  • 80
RavensKrag
  • 846
  • 1
  • 7
  • 9

5 Answers5

100

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.

x1a4
  • 19,152
  • 5
  • 39
  • 39
13

Another important point to note here is that << is also an operator, and it has lower or higher precedence than other operators. This may lead to unexpected results.

For example, << has higher precedence than the ternary operator, illustrated below:

arr1, arr2 = [], []

arr1.push true ? 1 : 0
arr1
# => [1] 

arr2 << true ? 1 : 0
arr2
# => [true] 
tdy
  • 26,545
  • 9
  • 43
  • 50
Santhosh
  • 26,663
  • 9
  • 73
  • 86
10

The reason why << does not work and push does is that:

  1. push can accept many arguments (which is what happens when you do *b).
  2. << only accepts a single argument.
David Weiser
  • 5,138
  • 4
  • 25
  • 35
9

The main difference between Array#<< and Array#push is

Array#<< # can be used to insert only single element in the Array

Array#push # can be used to insert more than single element in the Array

Another significant difference is, In case of inserting single element,

Array#<< is faster than Array#push

Benchmarking can help in finding out the performance of these two ways, find more here.

aardvarkk
  • 13,904
  • 7
  • 63
  • 93
Akshay Mohite
  • 2,048
  • 1
  • 14
  • 21
0

The push method appends an item to the end of the array.It can have more than one argument. << is used to initialize array and can have only one argument , adds an element at the end of array if already initialized.

Abhishek Singh
  • 6,068
  • 1
  • 21
  • 25