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
array.c
View on GitHub ↗
VALUE
rb_ary_last(int argc, const VALUE *argv, VALUE ary)
{
if (argc == 0) {
long len = RARRAY_LEN(ary);
if (len == 0) return Qnil;
return RARRAY_AREF(ary, len-1);
}
else {
return ary_take_first_or_last(argc, argv, ary, ARY_TAKE_LAST);
}
}
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.