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