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
class QueryParser def self.parse(query_string) new(query_string).parse end
Parsing nested query strings in Ruby
parsing
recursion
tokenization
Intermediate
9 steps
ruby
class Article < ApplicationRecord belongs_to :author, class_name: "User" has_many :taggings, dependent: :destroy has_many :tags, through: :taggings
How scopes compose in Rails
scopes
activerecord
query-composition
Intermediate
8 steps
python
import json import hashlib from datetime import timedelta
Idempotent payment endpoints in FastAPI
idempotency
redis
distributed-locking
Advanced
9 steps
ruby
class Order class InvalidTransition < StandardError; end TRANSITIONS = {
A state machine for order transitions in Ruby
state-machine
data-driven
error-handling
Intermediate
8 steps
ruby
class CreateOrderItems < ActiveRecord::Migration[7.1] def change create_table :order_items do |t| t.references :order, null: false, foreign_key: { on_delete: :cascade }
Enforcing order-item integrity in Rails
migrations
foreign-keys
validations
Intermediate
7 steps
php
<?php namespace App\Http\Middleware;
Idempotent requests with Laravel middleware
idempotency
middleware
caching
Advanced
8 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.