End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
Enumerable#first
first → element or nil
first(n) → array
enum.c
View on GitHub ↗
static VALUE
enum_first(int argc, VALUE *argv, VALUE obj)
{
struct MEMO *memo;
rb_check_arity(argc, 0, 1);
if (argc > 0) {
return enum_take(obj, argv[0]);
}
else {
memo = MEMO_NEW(Qnil, 0, 0);
rb_block_call(obj, id_each, 0, 0, first_i, (VALUE)memo);
return memo->v1;
}
}
Returns the first element or elements.
With no argument, returns the first element, or nil if there is none:
Example
(1..4).first # => 1 %w[a b c].first # => "a" {foo: 1, bar: 1, baz: 2}.first # => [:foo, 1] [].first # => nil
With integer argument n, returns an array containing the first n elements that exist:
Example
(1..4).first(2) # => [1, 2] %w[a b c d].first(3) # => ["a", "b", "c"] %w[a b c d].first(50) # => ["a", "b", "c", "d"] {foo: 1, bar: 1, baz: 2}.first(2) # => [[:foo, 1], [:bar, 1]] [].first(2) # => []