Syntax
enumerable.lazy.select { condition }.map { transformation }.take(count).forceExamples
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- Expected output: [1, 9, 25, 49]
- 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