Skip to content

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

instance method

Array#last

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

Returns elements from self; self is not modified.

When no argument is given, returns the last element:

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

If self is empty, returns nil.

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

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

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

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

If n == 0, returns an new empty Array:

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

Related: first.

See also #keep_if #length #join #map also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.1