Class LruHash

  1. lib/rufus/lru.rb
Parent: Hash

A Hash that has a max size. After the maxsize has been reached, the least recently used entries (LRU hence), will be discared to make room for the new entries.

require 'rubygems'
require 'rufus/lru'

h = LruHash.new(3)

5.times { |i| h[i] = "a" * i }

puts h.inspect # >> {2=>"aa", 3=>"aaa", 4=>"aaaa"}

h[:newer] = "b"

puts h.inspect # >> {:newer=>"b", 3=>"aaa", 4=>"aaaa"}

Methods

public class

  1. new

public instance

  1. []
  2. []=
  3. clear
  4. delete
  5. maxsize=
  6. merge!
  7. ordered_keys

protected instance

  1. remove_lru
  2. touch

Attributes

maxsize [R]

Public class methods

new (maxsize)

Initializes a LruHash with a given maxsize.

[show source]
    # File lib/rufus/lru.rb, line 60
60:   def initialize (maxsize)
61: 
62:     super()
63: 
64:     @maxsize = maxsize
65:     @lru_keys = []
66:   end

Public instance methods

[] (key)
[show source]
    # File lib/rufus/lru.rb, line 88
88:   def [] (key)
89: 
90:     value = super
91:     return nil unless value
92:     touch(key)
93: 
94:     value
95:   end
[]= (key, value)
[show source]
     # File lib/rufus/lru.rb, line 97
 97:   def []= (key, value)
 98: 
 99:     remove_lru
100:     super
101:     touch(key)
102: 
103:     value
104:   end
clear ()
[show source]
    # File lib/rufus/lru.rb, line 74
74:   def clear
75: 
76:     super
77:     @lru_keys.clear
78:   end
delete (key)
[show source]
     # File lib/rufus/lru.rb, line 113
113:   def delete (key)
114: 
115:     value = super
116:     @lru_keys.delete(key)
117: 
118:     value
119:   end
maxsize= (s)
[show source]
    # File lib/rufus/lru.rb, line 68
68:   def maxsize= (s)
69: 
70:     @maxsize = s
71:     remove_lru
72:   end
merge! (hash)
[show source]
     # File lib/rufus/lru.rb, line 106
106:   def merge! (hash)
107: 
108:     hash.each { |k, v| self[k] = v }
109: 
110:     # not using 'super', but in order not guaranteed at all...
111:   end
ordered_keys ()

Returns the keys with the lru in front.

[show source]
    # File lib/rufus/lru.rb, line 83
83:   def ordered_keys
84: 
85:     @lru_keys
86:   end

Protected instance methods

remove_lru ()

Makes sure that the hash fits its maxsize. If not, will remove the least recently used items.

[show source]
     # File lib/rufus/lru.rb, line 137
137:     def remove_lru
138: 
139:       while size >= @maxsize
140: 
141:         key = @lru_keys.delete_at(0)
142:         delete(key)
143:       end
144:     end
touch (key)

Puts the key on top of the lru ‘stack’. The bottom being the lru place.

[show source]
     # File lib/rufus/lru.rb, line 127
127:     def touch (key)
128: 
129:       @lru_keys.delete(key)
130:       @lru_keys << key
131:     end