Skip to content
instance method

Enumerable#first

() -> Elem?
(::_ToInt n) -> ::Array[Elem]
first → element or nil
first(n) → array

Returns the first element or elements.

With no argument, returns the first element, or nil if there is none:

Example
(1..4).first                   # => 1
%w[a b c].first                # => "a"
{foo: 1, bar: 1, baz: 2}.first # => [:foo, 1]
[].first                       # => nil

With integer argument n, returns an array containing the first n elements that exist:

Example
(1..4).first(2)                   # => [1, 2]
%w[a b c d].first(3)              # => ["a", "b", "c"]
%w[a b c d].first(50)             # => ["a", "b", "c", "d"]
{foo: 1, bar: 1, baz: 2}.first(2) # => [[:foo, 1], [:bar, 1]]
[].first(2)                       # => []
See also #find_index #flat_map #find_all #grep also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0