Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 864
RavensKrag Avatar asked May 13 '12 05:05

RavensKrag


People also ask

What is an array in Ruby?

An array is a data structure that represents a list of values, called elements. Arrays let you store multiple values in a single variable. In Ruby, arrays can contain any data type, including numbers, strings, and other Ruby objects.

Are arrays dynamic in Ruby?

Since Ruby arrays are dynamic, it isn't necessary to preallocate space for them. When you pass in a number by itself to Array#new, an Array with that many nil objects is created.

Is an array an object in Ruby?

What are array methods in Ruby? Array methods in Ruby are essentially objects that can store other objects. You can store any kind of object in an array. You can create an array by separating values by commas and enclosing your list with square brackets.

Does each return an array Ruby?

It's basically a "free" operation for Ruby to return the original array (otherwise it would return nil ). As a bonus it allows you to chain methods to further operate on the array if you want. A small point: if no block is present, [1,2,3]. each returns [1,2,3].


1 Answers

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.

like image 99
x1a4 Avatar answered Oct 12 '22 19:10

x1a4