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 "set" class FuzzySearch def initialize(candidates)
Building a ranked fuzzy search in Ruby
fuzzy-matching
levenshtein
ranking
Intermediate
9 steps
php
final class UserActivityStream { public function __construct( private readonly \PDO $db,
Streaming user activity with PHP generators
generators
pagination
lazy-evaluation
Intermediate
8 steps
ruby
class SearchIndexReconciler DEBOUNCE_WINDOW = 5.seconds def self.schedule(record)
Debouncing search reindex jobs in Rails
debouncing
background-jobs
caching
Advanced
7 steps
ruby
class ParamCoercer TYPES = { integer: ->(v) { Integer(v) }, float: ->(v) { Float(v) },
Coercing request params by schema in Ruby
lambdas
type-coercion
lookup-table
Intermediate
7 steps
ruby
module Api module V2 class ArticlesController < Api::BaseController before_action :set_article, only: %i[show update destroy]
Building a versioned JSON API controller in Rails
rest-api
serialization
pagination
Intermediate
10 steps
ruby
class ArticlesController < ApplicationController before_action :set_article, only: %i[show edit update destroy publish] def edit
Policy-based authorization in a Rails controller
authorization
policy-object
before-action
Intermediate
9 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.