Lazy Enumerators
Lazy evaluation.
Lazy Evaluation
Normally Enumerable methods process the entire collection at once. A lazy enumerator processes elements one at a time, only as needed. This lets you work with huge or even infinite sequences.
result = (1..Float::INFINITY).lazy.map { |n| n * 2 }.first(5)
p resultThe Problem with Eager Methods
Calling map on an infinite range without lazy would never finish, because it tries to build a complete result array first.
# Eager version would hang. Lazy completes instantly:
first_three = (1..Float::INFINITY).lazy.select(&:even?).first(3)
p first_threeAll lessons in this course
- Writing Custom each
- Including Enumerable
- Lazy Enumerators
- Enumerator Objects