ruby 41 lines · 7 steps

How an LRU cache works in Ruby

A least-recently-used cache built on Ruby's insertion-ordered Hash, evicting the oldest key once capacity is exceeded.

Explained by highlit
1class LRUCache
2 def initialize(capacity)
3 raise ArgumentError, "capacity must be positive" unless capacity.positive?
4 
5 @capacity = capacity
6 @store = {}
7 end
8 
9 def get(key)
10 return nil unless @store.key?(key)
11 
12 value = @store.delete(key)
13 @store[key] = value
14 value
15 end
16 
17 def put(key, value)
18 @store.delete(key)
19 @store[key] = value
20 @store.delete(@store.first.first) if @store.size > @capacity
21 value
22 end
23 
24 def fetch(key)
25 return get(key) if @store.key?(key)
26 
27 put(key, yield(key))
28 end
29 
30 def delete(key)
31 @store.delete(key)
32 end
33 
34 def keys
35 @store.keys
36 end
37 
38 def size
39 @store.size
40 end
41end
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Ruby Hashes preserve insertion order, so re-inserting a key moves it to the newest position for free.
  2. 2Deleting then re-adding a key on every access is the trick that keeps recency ordering accurate.
  3. 3Bounding a cache means evicting the oldest entry the moment size crosses capacity, not before.

Related explainers

Share this explainer

Here's the card — post it anywhere.

How an LRU cache works in Ruby — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code