Skip to content

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

instance method

Array#last

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

Returns elements from self, or nil; self is not modified.

With no argument given, returns the last element, or nil if self is empty:

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

With non-negative integer argument count given, returns a new array containing the trailing count elements of self, as available:

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

Related: see Methods for Fetching.

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