Codectionary / Developer documentation / Ruby

Lazy Enumerator Pipelines

Enumerator::Lazy delays transformations until values are requested. A finite take can safely bound an otherwise unbounded sequence. Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.

Syntax

enumerable.lazy.select { condition }.map { transformation }.take(count).force

Examples

Lazy Enumerator Pipelines

Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.

squares = (1..).lazy
  .select { |n| n.odd? }
  .map { |n| n * n }
  .take(4)
p squares.force
  1. Expected output: [1, 9, 25, 49]
  2. The endless range is consumed only far enough to find four odd values. force materializes that bounded lazy result.

Best practices

  • Apply a finite limit before forcing an unbounded enumerable.
  • Avoid side effects in lazy transformations when repeated enumeration would be surprising.

Runtime & versions

Ruby interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Ruby documentation

Specifications & further reading