Skip to content

End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

Range#first

first → object
first(n) → array

With no argument, returns the first element of self, if it exists:

Example
(1..4).first     # => 1
('a'..'d').first # => "a"

With non-negative integer argument n given, returns the first n elements in an array:

Example
(1..10).first(3) # => [1, 2, 3]
(1..10).first(0) # => []
(1..4).first(50) # => [1, 2, 3, 4]

Raises an exception if there is no first element:

Example
(..4).first # Raises RangeError
See also #exclude_end? #hash #eql? #include? also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.0