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

RubyArraysAppend

Ruby Problem Overview


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?

Ruby Solutions


Solution 1 - Ruby

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.

Solution 2 - Ruby

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] 

Solution 3 - Ruby

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.

Solution 4 - Ruby

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.

Solution 5 - Ruby

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRavensKragView Question on Stackoverflow
Solution 1 - Rubyx1a4View Answer on Stackoverflow
Solution 2 - RubySanthoshView Answer on Stackoverflow
Solution 3 - RubyDavid WeiserView Answer on Stackoverflow
Solution 4 - RubyAkshay MohiteView Answer on Stackoverflow
Solution 5 - RubyAbhishek SinghView Answer on Stackoverflow