70

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?

1

5 Answers 5

106

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.

3
  • 1
    To extend on this you can shorthand 'push' 2 arrays with +=. Use << to add a single value to an array.
    – TomDunning
    Commented May 13, 2012 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
    Commented Jun 6, 2013 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
    Commented Sep 2, 2016 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] 
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.
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.

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.