69

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
  • 23,994
  • 6
  • 61
  • 85
RavensKrag
  • 895
  • 1
  • 7
  • 9

5 Answers5

105

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,417
  • 5
  • 40
  • 40
  • 1
    To extend on this you can shorthand 'push' 2 arrays with +=. Use << to add a single value to an array. – TomDunning May 13 '12 at 18:54
  • @Isotope - That creates extra objects, so it should be considered an anti-pattern unless you really don't want to modify the first array. – x1a4 Jun 06 '13 at 19:42
  • 1
    I do believe the current version of Ruby does allow for the "<<" to take in more than one argument. – Al V Sep 02 '16 at 18:34
17

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
  • 36,675
  • 19
  • 86
  • 83
Santhosh
  • 28,097
  • 9
  • 82
  • 87
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,190
  • 4
  • 28
  • 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
  • 14,955
  • 7
  • 67
  • 96
Akshay Mohite
  • 2,168
  • 1
  • 16
  • 22
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
  • 23
  • 25