Method: Enumerable#first
- Defined in:
- enum.c
#first ⇒ nil #first(n) ⇒ Array
Returns the first element or elements.
With no argument, returns the first element, or nil if there is none:
(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:
(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) # => []
1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 |
# File 'enum.c', line 1337 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; } } |