In Files

Parent

Class/Module Index [+]

Quicksearch

LruHash

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"}

Attributes

maxsize[R]

Public Class Methods

new(maxsize) click to toggle source

Initializes a LruHash with a given maxsize.

# File lib/rufus/lru.rb, line 58
def initialize (maxsize)

  super()

  @maxsize = maxsize
  @lru_keys = []
end

Public Instance Methods

[](key) click to toggle source
# File lib/rufus/lru.rb, line 85
def [] (key)

  value = super
  return nil unless value
  touch(key)

  value
end
[]=(key, value) click to toggle source
# File lib/rufus/lru.rb, line 94
def []= (key, value)

  remove_lru
  super
  touch(key)

  value
end
clear() click to toggle source
# File lib/rufus/lru.rb, line 72
def clear

  super
  @lru_keys.clear
end
delete(key) click to toggle source
# File lib/rufus/lru.rb, line 110
def delete (key)

  value = super
  @lru_keys.delete(key)

  value
end
maxsize=(s) click to toggle source
# File lib/rufus/lru.rb, line 66
def maxsize= (s)

  @maxsize = s
  remove_lru
end
merge!(hash) click to toggle source
# File lib/rufus/lru.rb, line 103
def merge! (hash)

  hash.each { |k, v| self[k] = v }

  # not using 'super', but in order not guaranteed at all...
end
ordered_keys() click to toggle source

Returns the keys with the lru in front.

# File lib/rufus/lru.rb, line 80
def ordered_keys

  @lru_keys
end

Protected Instance Methods

remove_lru() click to toggle source

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

# File lib/rufus/lru.rb, line 132
def remove_lru

  while size >= @maxsize

    key = @lru_keys.delete_at(0)
    delete(key)
  end
end
touch(key) click to toggle source

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

# File lib/rufus/lru.rb, line 123
def touch (key)

  @lru_keys.delete(key)
  @lru_keys << key
end

[Validate]

Generated with the Darkfish Rdoc Generator 2.