Class: LRUCache
- Inherits:
-
Object
- Object
- LRUCache
- Defined in:
- lib/monkeysupport/lru_cache.rb
Instance Method Summary collapse
- #[](key) ⇒ Object
- #[]=(key, value) ⇒ Object
- #cleanup ⇒ Object
-
#initialize(size = 200, cleanup_threshold = size*2) ⇒ LRUCache
constructor
A new instance of LRUCache.
- #size ⇒ Object
Constructor Details
#initialize(size = 200, cleanup_threshold = size*2) ⇒ LRUCache
Returns a new instance of LRUCache.
5 6 7 8 9 10 11 12 13 14 |
# File 'lib/monkeysupport/lru_cache.rb', line 5 def initialize(size=200, cleanup_threshold=size*2) @size = size @cleanup_threshold = cleanup_threshold @cache = {} @access = [0]*size @counter = 0 end |
Instance Method Details
#[](key) ⇒ Object
21 22 23 24 |
# File 'lib/monkeysupport/lru_cache.rb', line 21 def [](key) # @cache[key][0] = @count @cache[key] end |
#[]=(key, value) ⇒ Object
16 17 18 19 |
# File 'lib/monkeysupport/lru_cache.rb', line 16 def []=(key, value) @cache[key] = [Time.now, value] cleanup if @cache.size > @cleanup_threshold end |
#cleanup ⇒ Object
26 27 28 29 30 31 |
# File 'lib/monkeysupport/lru_cache.rb', line 26 def cleanup num_delete = @cache.size - @size @cache.sort_by{|k,v|v[0]}[0...num_delete].each do |arr| @cache.delete(arr[0]) end end |
#size ⇒ Object
33 34 35 |
# File 'lib/monkeysupport/lru_cache.rb', line 33 def size @cache.size end |