class LRUCache

Public Class Methods

new(size = 10) click to toggle source
# File lib/lru_cache.rb, line 2
def initialize(size = 10)
  @size = size.to_i
  @store = {}
  @lru = []
end

Public Instance Methods

[](key) click to toggle source
# File lib/lru_cache.rb, line 21
def [](key)
  get(key)
end
[]=(key, value) click to toggle source
# File lib/lru_cache.rb, line 25
def []=(key, value)
  set(key, value)
end
delete(key) click to toggle source
# File lib/lru_cache.rb, line 33
def delete(key)
  @store.delete(key)
  @lru.delete(key)
end
get(key) click to toggle source
# File lib/lru_cache.rb, line 15
def get(key)
  return nil unless @store.key?(key)
  set_lru(key)
  @store[key]
end
keys() click to toggle source
# File lib/lru_cache.rb, line 29
def keys
  @store.keys
end
set(key, value = nil) click to toggle source
# File lib/lru_cache.rb, line 8
def set(key, value = nil)
  @store[key] = value
  set_lru(key)
  @store.delete(@lru.pop) if @lru.size > @size
  value
end

Private Instance Methods

set_lru(key) click to toggle source
# File lib/lru_cache.rb, line 39
def set_lru(key)
  @lru.unshift(@lru.delete(key) || key)
end