liveBook · Manning

Lazy enumerator

As explained in The Well-Grounded Rubyist, Fourth Edition

A lazy enumerator is a Ruby enumerator that defers producing elements until results are requested.

A lazy enumerator defers producing elements until results are requested. This makes operations such as select usable on infinitely large collections, because evaluation stops after enough results have been produced. section 10.12

(1..Float::INFINITY).select {|n| n % 3 == 0 }.first(10)

A non-lazy select over an infinite range never finishes, so first is never reached; adding lazy creates a demand-driven chain. section 10.12

Selecting multiples of three

`(1..Float::INFINITY).lazy.select { |n| n % 3 == 0 }.first(10)` produces `[3, 6, 9, 12, 15, 18, 21, 24, 27, 30]`. Alternatively, `take` remains lazy until `force` materializes the result: `my_enum.take(5).force`. section 10.12

Lazy FizzBuzz

A lazy map over `(1..Float::INFINITY)` can calculate FizzBuzz values and use `first(n)` to return only the requested prefix, such as the first 15 values.

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains lazy chains through select, first, take, and force, while stopping short of broader implementation internals.
Examples
Uses multiples of three from an infinite range, finite take and force calls, and a lazy FizzBuzz generator.
What it assumes
Builds from ranges and familiar Enumerable operations before introducing deferred evaluation.
What you can do after
Apply it via Ruby's lazy, select, map, first, take, and force methods to compute finite prefixes efficiently.
How it connects
Connects Enumerator with Enumerable operations, infinite collections, functional programming, and memory-conscious computation.

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.