ruby 49 lines · 8 steps

Building infinite sequences with lazy enumerators

Ruby's Enumerator plus .lazy lets you define endless streams and pull only the values you need.

Explained by highlit
1def collatz_lengths
2 Enumerator.new do |y|
3 n = 1
4 loop do
5 steps = 0
6 current = n
7 until current == 1
8 current = current.even? ? current / 2 : 3 * current + 1
9 steps += 1
10 end
11 y << [n, steps]
12 n += 1
13 end
14 end.lazy
15end
16 
17fibonacci = Enumerator.new do |y|
18 a, b = 0, 1
19 loop do
20 y << a
21 a, b = b, a + b
22 end
23end.lazy
24 
25primes = Enumerator.new do |y|
26 seen = []
27 candidate = 2
28 loop do
29 y << candidate if seen.none? { |p| (candidate % p).zero? }
30 seen << candidate if seen.none? { |p| (candidate % p).zero? }
31 candidate += 1
32 end
33end.lazy
34 
35long_collatz = collatz_lengths
36 .select { |_, steps| steps > 100 }
37 .map { |n, steps| { start: n, steps: steps } }
38 .first(5)
39 
40twin_primes = primes
41 .each_cons(2)
42 .select { |a, b| b - a == 2 }
43 .take(10)
44 .force
45 
46even_fibs = fibonacci
47 .select(&:even?)
48 .take_while { |f| f < 1_000_000 }
49 .to_a
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Enumerator.new with a yielder lets you describe a sequence's logic separately from how many values you consume.
  2. 2Calling .lazy defers computation so filters and maps run element-by-element instead of over a whole collection.
  3. 3A terminating operation like first, take, or to_a is what actually drives an otherwise infinite stream.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building infinite sequences with lazy enumerators — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code