Created
June 19, 2014 08:16
-
-
Save v2e4lisp/de0a1b18b3c6acd2fb7d to your computer and use it in GitHub Desktop.
simple ruby LRU cache
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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