Skip to content

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

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.

See also #reverse! #rindex #reverse #rotate also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.1