instance method · added in Ruby 4.0
Array#rfind
() { (Elem) -> ::boolish } -> Elem?
() -> ::Enumerator[Elem, Elem?]
[T] (::Enumerable::_NotFound[T] ifnone) { (Elem) -> ::boolish } -> (Elem | T)
[T] (::Enumerable::_NotFound[T] ifnone) -> ::Enumerator[Elem, Elem | T]
rfind(if_none_proc = nil) {|element| ... } → object or nil
rfind(if_none_proc = nil) → enumerator
array.c
View on GitHub ↗
static VALUE
rb_ary_rfind(int argc, VALUE *argv, VALUE ary)
{
VALUE if_none;
long len, idx;
RETURN_ENUMERATOR(ary, argc, argv);
if_none = rb_check_arity(argc, 0, 1) ? argv[0] : Qnil;
idx = RARRAY_LEN(ary);
while (idx--) {
VALUE elem = RARRAY_AREF(ary, idx);
if (RTEST(rb_yield(elem))) {
return elem;
}
len = RARRAY_LEN(ary);
idx = (idx >= len) ? len : idx;
}
if (!NIL_P(if_none)) {
return rb_funcallv(if_none, idCall, 0, 0);
}
return Qnil;
}
Returns the last element for which the block returns a truthy value.
With a block given, calls the block with successive elements of the array in reverse order; returns the first element for which the block returns a truthy value:
Example
[1, 2, 3, 4, 5, 6].rfind {|element| element < 5} # => 4
If no such element is found, calls if_none_proc and returns its return value.
Example
[1, 2, 3, 4].rfind(proc {0}) {|element| element < -2} # => 0
With no block given, returns an Enumerator.
Ruby version changes
-
4.0
-
Array#rfindhas been added as a more efficient alternative toarray.reverse_each.find[Feature #21678]
-