liveBook · Manning

Iterator

As explained in The Well-Grounded Rubyist, Fourth Edition

An iterator is a method or construct that automatically traverses the elements of a collection.

A Ruby iterator is a method that expects a code block. The method can run that block with `yield`, passing control back to the block before continuing. Iterators use this pattern to repeat work or process values. section 6.3.1 section 6.5

Iterating over bytes

`each_byte` runs the supplied block once for each byte in a string. For example, `str.each_byte { |b| puts b }` prints the string's byte values. section 10.9.3

An iterator and an enumerator are related, but they are different kinds of things:

  • An iterator is a method; its call runs as a whole and does not retain position between calls. section 10.10.3
  • An enumerator is an object that can remember its position. Many built-in iterators return one when called without a block, allowing further method calls to be chained. section 10.10.3 section 10.9.3
>> str.each_byte
=> #<Enumerator: "Hello":each_byte>

This blockless `each_byte` call returns an enumerator instead of immediately iterating through the string. section 10.9.3

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains block-and-yield mechanics and contrasts iterators with stateful enumerators, without detailing every iterator's implementation.
Examples
Uses loop with puts and String#each_byte to demonstrate block-based iteration and blockless calls.
What you can do after
Apply iterators by supplying a block, or call many built-in iterators without one to obtain an enumerator.
How it connects
Connects code blocks, yield, control flow, collections, and enumerators.

Also explained in

Compare how 15 books explain iterator →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.