Blocks and Enumeration

In our program that wrote out the results of our word frequency analysis, we had the following loop:

 top_five.​reverse_each​ ​do​ |word, count|
  puts ​"​​#{​word​}​​: ​​#{​count​}​​"
 end

The method reverse_each is an example of an iterator—a general term for a method that invokes a block of code repeatedly. Ruby also uses the term enumerator for such a method.

The most general iterator in Ruby is each, which takes a block and invokes the block once for each element in the collection. In this case, we’re using reverse_each, a shortcut method that invokes the block once for each element of the list, but in reverse order.

Enumerator methods can have different behaviors beyond just executing the block of code. A Ruby ...

Get Programming Ruby 3.3 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.