Skip to content

Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →

instance method

Array#first

array.first → object or nil
array.first(n) → new_array

Returns elements from self; does not modify self.

When no argument is given, returns the first element:

Example
a = [:foo, 'bar', 2]
a.first # => :foo
a # => [:foo, "bar", 2]

If self is empty, returns nil.

When non-negative Integer argument n is given, returns the first n elements in a new Array:

Example
a = [:foo, 'bar', 2]
a.first(2) # => [:foo, "bar"]

If n >= array.size, returns all elements:

Example
a = [:foo, 'bar', 2]
a.first(50) # => [:foo, "bar", 2]

If n == 0 returns an new empty Array:

Example
a = [:foo, 'bar', 2]
a.first(0) # []

Related: last.

See also #find_index #flatten #filter! #flatten! also in 4.1 · 4.0 · 3.4 · 3.2 · 3.1 · 3.0