0Pricing
Ruby Academy · Lesson

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 result

The 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_three

All lessons in this course

  1. Writing Custom each
  2. Including Enumerable
  3. Lazy Enumerators
  4. Enumerator Objects
← Back to Ruby Academy