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
class ToastBroadcaster include ActionView::RecordIdentifier def self.broadcast_to(user, message:, type: :notice)
How Turbo Stream toasts broadcast in Rails
turbo-streams
service-object
real-time
Intermediate
6 steps
ruby
class TemplateInterpolator PLACEHOLDER = /\{\{\s*([\w.]+)\s*\}\}/ def initialize(strict: false)
Interpolating templates with dotted keys in Ruby
regex
string-interpolation
hash-traversal
Intermediate
6 steps
ruby
class KeyTransformer def self.camelize(data) new.camelize(data) end
Recursively camelizing nested Ruby data
recursion
data-transformation
pattern-matching
Intermediate
7 steps
ruby
module Paginatable extend ActiveSupport::Concern private
A reusable pagination concern in Rails
pagination
concerns
http-headers
Intermediate
8 steps
ruby
class Api::MessagesController < ApiController before_action :authenticate_api_key! rate_limit to: 100,
Layered API rate limiting in Rails
rate-limiting
api-authentication
throttling
Intermediate
9 steps
go
package scheduler import ( "container/heap"
A priority job queue with Go's container/heap
priority-queue
heap
interfaces
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-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.