Skip to content

Instantly share code, notes, and snippets.

@v2e4lisp
Created June 19, 2014 08:16
Show Gist options
  • Save v2e4lisp/de0a1b18b3c6acd2fb7d to your computer and use it in GitHub Desktop.
Save v2e4lisp/de0a1b18b3c6acd2fb7d to your computer and use it in GitHub Desktop.
simple ruby LRU cache
class LRU
attr_reader :content
attr_accessor :max
def initialize(max, hash={})
@max = max
@content = hash
end
def [](key)
content[key] = content.delete(key) if content.has_key? key
end
alias_method :get, :[]
def []=(key, value)
content.delete key if content.has_key? key
content.delete(content.first.first) if content.length == max
content[key] = value
end
alias_method :set, :[]=
end
lru = LRU.new(2)
lru.set :a, :a
lru.set :b, :b
lru.set :a, :a
lru.get :b
lru.set :c, :c
puts lru.content
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment