instance method
Array#detect
(?::Proc ifnone) { (Elem) -> ::boolish } -> Elem?
(?::Proc ifnone) -> ::Enumerator[Elem, Elem?]
detect(*args)
array.c
View on GitHub ↗
static VALUE
rb_ary_find(int argc, VALUE *argv, VALUE ary)
{
VALUE if_none;
long idx;
RETURN_ENUMERATOR(ary, argc, argv);
if_none = rb_check_arity(argc, 0, 1) ? argv[0] : Qnil;
for (idx = 0; idx < RARRAY_LEN(ary); idx++) {
VALUE elem = RARRAY_AREF(ary, idx);
if (RTEST(rb_yield(elem))) {
return elem;
}
}
if (!NIL_P(if_none)) {
return rb_funcallv(if_none, idCall, 0, 0);
}
return Qnil;
}
Alias of #find
Returns the first element for which the block returns a truthy value.
With a block given, calls the block with successive elements of the array; returns the first element for which the block returns a truthy value:
Example
[1, 3, 5].find {|element| element > 2} # => 3
If no such element is found, calls if_none_proc and returns its return value.
Example
[1, 3, 5].find(proc {-1}) {|element| element > 12} # => -1
With no block given, returns an Enumerator.