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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Enumerator.new with a yielder lets you describe a sequence's logic separately from how many values you consume.
- 2Calling .lazy defers computation so filters and maps run element-by-element instead of over a whole collection.
- 3A terminating operation like first, take, or to_a is what actually drives an otherwise infinite stream.
Related explainers
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 steps
python
import random from typing import Iterator, List
How reservoir sampling picks k items
reservoir-sampling
streaming
randomness
Intermediate
5 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-infinite-sequences-with-lazy-enumerators-explained-ruby-a9e4/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.