Ruby Newbie homepage Ruby Newbie homepage

How to use

Quick guide

Official content
Returns elements from self; does not modify self.
When no argument is given, returns the first element:
a = [:foo, 'bar', 2]
a.first # => :foo
a # => [:foo, "bar", 2]
If self is empty, returns nil.
When non-negative Integer argument n is given, returns the first n elements in a new Array:
a = [:foo, 'bar', 2]
a.first(2) # => [:foo, "bar"]
If n >= array.size, returns all elements:
a = [:foo, 'bar', 2]
a.first(50) # => [:foo, "bar", 2]
If n == 0 returns an new empty Array:
a = [:foo, 'bar', 2]
a.first(0) # []
Related: last.
 
               static VALUE
rb_ary_first(int argc, VALUE *argv, VALUE ary)
{
    if (argc == 0) {
        if (RARRAY_LEN(ary) == 0) return Qnil;
        return RARRAY_AREF(ary, 0);
    }
    else {
        return ary_take_first_or_last(argc, argv, ary, ARY_TAKE_FIRST);
    }
}
            

Was this page useful?