End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
Enumerable#find
enum.find(ifnone = nil) { |obj| block } → obj or nil
enum.find(ifnone = nil) → an_enumerator
enum.c
View on GitHub ↗
static VALUE
enum_find(int argc, VALUE *argv, VALUE obj)
{
struct MEMO *memo;
VALUE if_none;
if_none = rb_check_arity(argc, 0, 1) ? argv[0] : Qnil;
RETURN_ENUMERATOR(obj, argc, argv);
memo = MEMO_NEW(Qundef, 0, 0);
rb_block_call(obj, id_each, 0, 0, find_i, (VALUE)memo);
if (memo->u3.cnt) {
return memo->v1;
}
if (!NIL_P(if_none)) {
return rb_funcallv(if_none, id_call, 0, 0);
}
return Qnil;
}
Passes each entry in enum to block. Returns the first for which block is not false. If no object matches, calls ifnone and returns its result when it is specified, or returns nil otherwise.
If no block is given, an enumerator is returned instead.
Example
(1..100).detect #=> #<Enumerator: 1..100:detect> (1..100).find #=> #<Enumerator: 1..100:find> (1..10).detect { |i| i % 5 == 0 && i % 7 == 0 } #=> nil (1..10).find { |i| i % 5 == 0 && i % 7 == 0 } #=> nil (1..10).detect(-> {0}) { |i| i % 5 == 0 && i % 7 == 0 } #=> 0 (1..10).find(-> {0}) { |i| i % 5 == 0 && i % 7 == 0 } #=> 0 (1..100).detect { |i| i % 5 == 0 && i % 7 == 0 } #=> 35 (1..100).find { |i| i % 5 == 0 && i % 7 == 0 } #=> 35