Ruby Newbie homepage Ruby Newbie homepage

How to use

Quick guide

Official content
Iterates backwards over array elements.
When a block given, passes, in reverse order, each element to the block; returns self:
a = [:foo, 'bar', 2]
a.reverse_each {|element|  puts "#{element.class} #{element}" }
Output:
Integer 2
String bar
Symbol foo
Allows the array to be modified during iteration:
a = [:foo, 'bar', 2]
a.reverse_each {|element| puts element; a.clear if element.to_s.start_with?('b') }
Output:
2
bar
When no block given, returns a new Enumerator:
a = [:foo, 'bar', 2]
e = a.reverse_each
e # => #<Enumerator: [:foo, "bar", 2]:reverse_each>
a1 = e.each {|element|  puts "#{element.class} #{element}" }
Output:
Integer 2
String bar
Symbol foo
Related: each, each_index.
 
               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;
}
            

Was this page useful?