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 "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
rust
use std::f64::consts::PI; #[derive(Debug, Clone, Copy)] pub struct LatLng {
Building geographic bounding boxes in Rust
geospatial
value-types
option
Intermediate
7 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
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-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.