End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
Array#first
array.first → object or nil
array.first(n) → new_array
array.c
View on GitHub ↗
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);
}
}
Returns elements from self; does not modify self.
When no argument is given, returns the first element:
Example
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:
Example
a = [:foo, 'bar', 2] a.first(2) # => [:foo, "bar"]
If n >= array.size, returns all elements:
Example
a = [:foo, 'bar', 2] a.first(50) # => [:foo, "bar", 2]
If n == 0 returns an new empty Array:
Example
a = [:foo, 'bar', 2] a.first(0) # []
Related: last.