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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Ruby Hashes preserve insertion order, so re-inserting a key moves it to the newest position for free.
- 2Deleting then re-adding a key on every access is the trick that keeps recency ordering accurate.
- 3Bounding a cache means evicting the oldest entry the moment size crosses capacity, not before.
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
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 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
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
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/how-an-lru-cache-works-in-ruby-explained-ruby-fa09/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.