first(...) public

Returns the first element, or the first n elements, of the array. If the array is empty, the first form returns nil, and the second form returns an empty array.

a = [ "q", "r", "s", "t" ]
a.first    #=> "q"
a.first(1) #=> ["q"]
a.first(3) #=> ["q", "r", "s"]
Show source
Register or log in to add new notes.
April 16, 2009
1 thank

Extracting the First Element

To extract the first element from an Array, use shift:

array = [ 1, 2, 3 ]           # => [ 1, 2, 3 ]
array.first                   # => 1
array                         # => [ 1, 2, 3 ]
array.shift                   # => 1
array                         # => [ 2, 3 ]