Lesson contents

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

  1. Start with 1, 2, 3, …
  2. Do this Double the first two
  3. Result 2 → 4
Requesting two results makes the lazy enumerator stop after doubling 1 and 2.
lesson.rb
numbers = (1..100).lazy.map { |n| n * 2 }
puts numbers.first(2)
Output
2
4
Advertisements

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.

First preview: 8. Full traversal: 8 and 14. Batch total: 22.
Preview a reading, then total the batch

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
lesson.rb
readings = [-1, 4, 7]
positive = readings.lazy.select(&:positive?).map { |value| value * 2 }
puts positive.first
puts positive.sum
Output
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.

Ruby language documentation

Related tags

  • Ruby
  • Enumerable
  • blocks
  • lazy iteration