0
0
Rubyprogramming~5 mins

Lazy enumerators in Ruby

Choose your learning style9 modes available
Introduction

Lazy enumerators help you work with big or infinite lists without using too much memory. They only do work when needed.

When you want to process a large list but avoid loading it all at once.
When you want to create an infinite sequence like counting numbers.
When you want to chain many steps but delay the work until the result is needed.
When you want to save memory and speed by not creating intermediate arrays.
Syntax
Ruby
enum = (1..Float::INFINITY).lazy
result = enum.select { |x| x % 2 == 0 }.map { |x| x * 10 }.first(5)

Use .lazy on an enumerable to make it lazy.

Lazy enumerators delay work until you ask for results, like with first or take.

Examples
This creates an infinite lazy list of numbers and takes the first 5.
Ruby
numbers = (1..Float::INFINITY).lazy
first_five = numbers.first(5)
This selects even numbers lazily from 1 to 10, then converts to an array.
Ruby
lazy_enum = (1..10).lazy.select { |x| x.even? }
result = lazy_enum.to_a
This doubles numbers lazily and takes the first 3 results.
Ruby
lazy_enum = (1..Float::INFINITY).lazy.map { |x| x * 2 }
first_three = lazy_enum.first(3)
Sample Program

This program creates an infinite list of numbers lazily, picks even ones, multiplies them by 3, and prints the first 5 results.

Ruby
numbers = (1..Float::INFINITY).lazy
# Select even numbers, multiply by 3, take first 5
result = numbers.select { |x| x.even? }.map { |x| x * 3 }.first(5)
puts result.join(", ")
OutputSuccess
Important Notes

Lazy enumerators do not create intermediate arrays, saving memory.

Use first or take to get results from lazy enumerators.

Be careful with infinite enumerators: always limit results to avoid endless loops.

Summary

Lazy enumerators delay work until needed, saving memory and time.

They are great for big or infinite lists.

Use .lazy to create them and first or take to get results.