ruby
33 lines · 7 steps
Building an enumerable linked list in Ruby
A hand-rolled singly linked list that gains map, select, and more for free by implementing each.
Explained by
highlit
1class LinkedList
2 include Enumerable
3
4 Node = Struct.new(:value, :next_node)
5
6 def initialize
7 @head = nil
8 @tail = nil
9 end
10
11 def push(value)
12 node = Node.new(value, nil)
13 if @head.nil?
14 @head = node
15 else
16 @tail.next_node = node
17 end
18 @tail = node
19 self
20 end
21 alias << push
22
23 def each
24 return to_enum(:each) unless block_given?
25
26 current = @head
27 while current
28 yield current.value
29 current = current.next_node
30 end
31 self
32 end
33end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Including Enumerable and defining a single each method grants you the entire collection API for free.
- 2Tracking both head and tail pointers makes appending an O(1) operation instead of walking the list each time.
- 3Returning self from mutating methods like push enables fluent chaining, while to_enum gives callers an external enumerator.
Related explainers
ruby
require "csv" class SalesReport def initialize(path)
Aggregating CSV sales data in Ruby
data-aggregation
memoization
group_by
Intermediate
6 steps
ruby
module DurationFormatter UNITS = [ ['week', 604_800], ['day', 86_400],
Turning seconds into human-readable durations in Ruby
greedy-decomposition
modular-arithmetic
formatting
Intermediate
7 steps
go
package cache import ( "container/list"
Building a generic LRU cache in Go
lru-cache
generics
linked-list
Intermediate
8 steps
ruby
class Comment < ApplicationRecord belongs_to :post belongs_to :author, class_name: "User"
Live-updating comments with Turbo in Rails
turbo-streams
callbacks
associations
Intermediate
8 steps
ruby
require 'json' require 'set' class SensitiveScrubber
Recursively scrubbing secrets from JSON
recursion
data-masking
pattern-matching
Intermediate
7 steps
ruby
class ReportBatcher BATCH_SIZE = 500 def initialize(account)
Batching monthly email summaries in Rails
batching
service-object
background-jobs
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-an-enumerable-linked-list-in-ruby-explained-ruby-8063/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.