Ruby Newbie homepage Ruby Newbie homepage

How to use

Quick guide

Official content
Returns elements from self; self is not modified.
When no argument is given, returns the last element:
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:
a = [:foo, 'bar', 2]
a.last(2) # => ["bar", 2]
If n >= array.size, returns all elements:
a = [:foo, 'bar', 2]
a.last(50) # => [:foo, "bar", 2]
If n == 0, returns an new empty Array:
a = [:foo, 'bar', 2]
a.last(0) # []
Related: first.
 
               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);
    }
}
            

Was this page useful?