January 2024
Intermediate to advanced
718 pages
20h 15m
English
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 ...
Read now
Unlock full access