Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
instance method
Array#reverse_each
() { (Elem element) -> void } -> self
() -> ::Enumerator[Elem, self]
reverse_each {|element| ... } → self
reverse_each → Enumerator
array.c
View on GitHub ↗
static VALUE
rb_ary_reverse_each(VALUE ary)
{
rb_len_t len;
RETURN_SIZED_ENUMERATOR(ary, 0, 0, ary_enum_length);
len = RARRAY_LEN(ary);
while (len--) {
rb_len_t nlen;
rb_yield(RARRAY_AREF(ary, len));
nlen = RARRAY_LEN(ary);
if (nlen < len) {
len = nlen;
}
}
return ary;
}
When a block given, iterates backwards over the elements of self, passing, in reverse order, each element to the block; returns self:
Example
a = [] [0, 1, 2].reverse_each {|element| a.push(element) } a # => [2, 1, 0]
Allows the array to be modified during iteration:
Example
a = ['a', 'b', 'c'] a.reverse_each {|element| a.clear if element.start_with?('b') } a # => []
When no block given, returns a new Enumerator.
Related: see Methods for Iterating.