End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
Array#reverse_each
array.reverse_each {|element| ... } → self
array.reverse_each → Enumerator
array.c
View on GitHub ↗
static VALUE
rb_ary_reverse_each(VALUE ary)
{
long len;
RETURN_SIZED_ENUMERATOR(ary, 0, 0, ary_enum_length);
len = RARRAY_LEN(ary);
while (len--) {
long nlen;
rb_yield(RARRAY_AREF(ary, len));
nlen = RARRAY_LEN(ary);
if (nlen < len) {
len = nlen;
}
}
return ary;
}
Iterates backwards over array elements.
When a block given, passes, in reverse order, each element to the block; returns self:
Example
a = [:foo, 'bar', 2] a.reverse_each {|element| puts "#{element.class} #{element}" }
Output:
Example
Integer 2 String bar Symbol foo
Allows the array to be modified during iteration:
Example
a = [:foo, 'bar', 2] a.reverse_each {|element| puts element; a.clear if element.to_s.start_with?('b') }
Output:
Example
2 bar
When no block given, returns a new Enumerator:
Example
a = [:foo, 'bar', 2] e = a.reverse_each e # => #<Enumerator: [:foo, "bar", 2]:reverse_each> a1 = e.each {|element| puts "#{element.class} #{element}" }
Output:
Example
Integer 2 String bar Symbol foo
Related: each, each_index.