Ruby — Lazy enumerators and blocks
Use lazy enumeration to filter and transform a sequence when the consumer requests results.
A simple example
Take two lazy results
- Start with 1, 2, 3, …
- Do this Double the first two
- Result 2 → 4
numbers = (1..100).lazy.map { |n| n * 2 }
puts numbers.first(2)
2 4
Build a lazy enumeration pipeline
lazy delays transformation until a terminal operation requests elements. The array-backed enumerable can be traversed again, so sum includes both doubled values after first has returned.
The first valid reading, 4, becomes 8 when doubled. This sequence starts from an array, so a fresh traversal can process both 4 and 7. Their scaled values add up to 22.
Run the example
Ruby 2.7 or later. Run these commands from the directory containing the example.
ruby lesson.rb
readings = [-1, 4, 7]
positive = readings.lazy.select(&:positive?).map { |value| value * 2 }
puts positive.first
puts positive.sum
8 22
The first transformed value is 8. A full traversal of this array-backed sequence then sums 8 and 14 to get 22.
Try it yourself
What would first(2) return?
Check your answer
An array containing 8 and 14. The consumer asks for two transformed values.