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?
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.
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.
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.
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].
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With