Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →
instance method
Array#last
array.last → object or nil
array.last(n) → new_array
array.rb
View on GitHub ↗
# File tmp/rubies/ruby-3.3.0/array.rb, line 145
def last n = unspecified = true
if Primitive.mandatory_only?
Primitive.attr! :leaf
Primitive.cexpr! %q{ ary_last(self) }
else
if unspecified
Primitive.cexpr! %q{ ary_last(self) }
else
Primitive.cexpr! %q{ ary_take_first_or_last_n(self, NUM2LONG(n), ARY_TAKE_LAST) }
end
end
end
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 Integer 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.