Class: LRUCache
- Inherits:
-
Object
- Object
- LRUCache
- Defined in:
- lib/lru_cache.rb
Instance Method Summary collapse
- #[](key) ⇒ Object
- #[]=(key, value) ⇒ Object
- #delete(key) ⇒ Object
- #get(key) ⇒ Object
-
#initialize(size = 10) ⇒ LRUCache
constructor
A new instance of LRUCache.
- #keys ⇒ Object
- #set(key, value = nil) ⇒ Object
Constructor Details
#initialize(size = 10) ⇒ LRUCache
Returns a new instance of LRUCache.
2 3 4 5 6 |
# File 'lib/lru_cache.rb', line 2 def initialize(size = 10) @size = size.to_i @store = {} @lru = [] end |
Instance Method Details
#[](key) ⇒ Object
21 22 23 |
# File 'lib/lru_cache.rb', line 21 def [](key) get(key) end |
#[]=(key, value) ⇒ Object
25 26 27 |
# File 'lib/lru_cache.rb', line 25 def []=(key, value) set(key, value) end |
#delete(key) ⇒ Object
33 34 35 36 |
# File 'lib/lru_cache.rb', line 33 def delete(key) @store.delete(key) @lru.delete(key) end |
#get(key) ⇒ Object
15 16 17 18 19 |
# File 'lib/lru_cache.rb', line 15 def get(key) return nil unless @store.key?(key) set_lru(key) @store[key] end |
#keys ⇒ Object
29 30 31 |
# File 'lib/lru_cache.rb', line 29 def keys @store.keys end |
#set(key, value = nil) ⇒ Object
8 9 10 11 12 13 |
# 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 |