Class Rufus::Lru::Hash
In: 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"}

One may want to squeeze hash manually

  h = LruHash.new(3, true)
  # or h.squeeze_on_demand=true after h is created
  .
  .
  h.squeeze!

If a value has destructor method clear it may be called upon the key-value removal

  h = LruHash.new(33, does_not_matter, true)
  # or h.clear_value_on_removal=true after h is created

Nota bene: this class is not thread-safe. If you need something thread-safe, use Rufus::Lru::SynchronizedHash.

Methods

[]   []=   auto_squeeze=   auto_squeeze?   call_on_removal   clear   delete   do_squeeze!   maxsize=   merge!   new   squeeze!   to_h   touch  

External Aliases

lru_keys -> ordered_keys
  Returns the keys with the lru in front.

Attributes

lru_keys  [R] 
maxsize  [R] 
on_removal  [RW] 

Public Class methods

Initializes a LruHash with a given maxsize.

Options:

  • :auto_squeeze defaults to true
  • :on_removal accepts false, a symbol or a lambda.
    • False is the default, values are removed, nothing special happens.
    • A symbol can be used to point to a method like :clear or :destroy that has to be called on the value just removed
    • A lambda/proc can be set, it‘s thus called (and passed the removed value as argument) each time a removal occurs

Public Instance methods

Returns a regular Hash with the entries in this hash.

Protected Instance methods

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

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

[Validate]