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

Walkthrough

Space play step click any line
Three takeaways
  1. 1Including Enumerable and defining a single each method grants you the entire collection API for free.
  2. 2Tracking both head and tail pointers makes appending an O(1) operation instead of walking the list each time.
  3. 3Returning self from mutating methods like push enables fluent chaining, while to_enum gives callers an external enumerator.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building an enumerable linked list in Ruby — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code