Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →
instance method
Enumerable#find
() { (Elem) -> ::boolish } -> Elem?
() -> ::Enumerator[Elem, Elem?]
[T] (::Enumerable::_NotFound[T] ifnone) { (Elem) -> ::boolish } -> (Elem | T)
[T] (::Enumerable::_NotFound[T] ifnone) -> ::Enumerator[Elem, Elem | T]
find(if_none_proc = nil) {|element| ... } → object or nil
find(if_none_proc = nil) → 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);
if (rb_block_pair_yield_optimizable())
rb_block_call2(obj, id_each, 0, 0, find_i_fast, (VALUE)memo, RB_BLOCK_NO_USE_PACKED_ARGS);
else
rb_block_call2(obj, id_each, 0, 0, find_i, (VALUE)memo, RB_BLOCK_NO_USE_PACKED_ARGS);
if (memo->u3.cnt) {
return memo->v1;
}
if (!NIL_P(if_none)) {
return rb_funcallv(if_none, id_call, 0, 0);
}
return Qnil;
}
Returns the first element for which the block returns a truthy value.
With a block given, calls the block with successive elements of the collection; returns the first element for which the block returns a truthy value:
Example
(0..9).find {|element| element > 2} # => 3
If no such element is found, calls if_none_proc and returns its return value.
Example
(0..9).find(proc {false}) {|element| element > 12} # => false {foo: 0, bar: 1, baz: 2}.find {|key, value| key.start_with?('b') } # => [:bar, 1] {foo: 0, bar: 1, baz: 2}.find(proc {[]}) {|key, value| key.start_with?('c') } # => []
With no block given, returns an Enumerator.