10.5. Relatives of each

Enumerable makes several methods available to you that are similar to each, in that they go through the whole collection and yield elements from it, not stopping until they’ve gone all the way through (and in one case, not even then!). Each member of this family of methods has its own particular semantics and niche. The methods include reverse_each, each_with_index, each_slice, each_cons, cycle, and inject. We’ll look at them in that order.

10.5.1. reverse_each

The reverse_each method does what it sounds like it will do: it iterates backwards through an enumerable. For example, the code

[1,2,3].reverse_each {|e| puts e * 10 }

produces this output:

30
20
10

You have to be careful with reverse_each: don’t use it on an infinite ...

Get The Well-Grounded Rubyist, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.