Skip to content
instance method

Array#first

() -> Elem
(::int n) -> ::Array[Elem]
first → object or nil
first(count) → new_array

Returns elements from self, or nil; does not modify self.

With no argument given, returns the first element (if available):

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

If self is empty, returns nil.

Example
[].first # => nil

With a non-negative integer argument count given, returns the first count elements (as available) in a new array:

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

Related: see Methods for Querying.

See also #find_index #flatten #find #flatten! also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0