Ruby Method of the Day - Array.<< and Array.push

Posted by Kelly McCauley on Oct 26, 2007

Signature

array << object           #=> array
array.push(object1, ...)  #=> array

array << object appends object to the end of array and returns array (thus allowing the chaining of multiple calls to <<). array.push(object1, ...) appends all arguments to the end of array and returns array.

Examples

1
2
3
4
5
6
7
8
9
10
11
12
a = [1]           #=> [1]
a << 2            #=> [1, 2]
a << 3 << 4       #=> [1, 2, 3, 4]
a << [5, 6]       #=> [1, 2, 3, 4, [5, 6]]

b = []
b << 1 << "foo" << 1.34534 << :bar  #=> [1, "foo", 1.34534, :bar]

a = [1]           #=> [1]
a.push(2)         #=> [1, 2]
a.push(3,4)       #=> [1, 2, 3, 4]
a.push([5,6])     #=> [1, 2, 3, 4, [5, 6]]

Documentation Reference

Ruby version 1.8.6

www.ruby-doc.org : Array.<<, Array.push