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
module RequestTagging class Middleware def initialize(app) @app = app
Per-request context with CurrentAttributes in Rails
middleware
thread-safety
logging
Intermediate
7 steps
java
@Component public class HeaderMergeFilter { private static final String PER_REQUEST_HEADERS = HeaderMergeFilter.class.getName() + ".headers";
Merging default and per-request headers in Spring
webclient
filters
http-headers
Intermediate
8 steps
ruby
class Spellchecker ALPHABET = ('a'..'z').to_a.freeze def initialize(dictionary)
Building a Norvig-style spellchecker in Ruby
edit-distance
levenshtein
dynamic-programming
Advanced
10 steps
ruby
class Order < ApplicationRecord belongs_to :customer has_many :line_items has_many :products, through: :line_items
How scopes compose in a Rails model
scopes
activerecord
subqueries
Intermediate
7 steps
ruby
require "charlock_holmes" class TextFileNormalizer DEFAULT_CONFIDENCE = 60
Normalizing text files to clean UTF-8 in Ruby
encoding
text-processing
file-io
Intermediate
8 steps
ruby
require 'date' require 'set' class BusinessDayCalculator
Counting business days in Ruby
dates
sets
ranges
Intermediate
8 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.