Created: 2008-04-01 00:53
Updated: 2017-12-08 16:50
License: mit


Build Status Gem Version

LruHash class, a Hash with a max size, controlled by a LRU mechanism.

getting it

gem install rufus-lru

or better, simply add to your Gemfile

gem 'rufus-lru'


It's a regular hash, but you have to set a maxsize at instantiation.

Once the maxsize is reached, the hash will discard the element that was the least recently used (hence LRU).

require 'rufus-lru'

h =

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

Rufus::Lru::Hash isn't thread-safe, if you need something that is, use Rufus::Lru::SynchronizedHash

require 'rufus-lru'

h =

# ...

It's possible to squeeze LruHash manually:

h =, :auto_squeeze => false)
  # or
#h =
#h.auto_squeeze = false

# ... values keep accumulating ...

# when a squeeze is needed...

LruHash accepts on initialization a :on_removal option. It can be set to a Symbol, which is then used as the method name to call on the value just removed:

require 'rufus-lru'

class ObjectWithDestructor; def clear; puts 'Destructor called'; end; end

h =, :on_removal => :clear)

h[:one] =
h[:two] = nil # :one is being removed >> "Destructor called"

Or it can be set to a lambda:

require 'rufus-lru'

seen = []
h =
  :on_removal => lambda { |val| seen << val.object_id })

h[:one] = 'abc'
h[:two] = 'xyz'

# seen ends up with the object_id of the 'abc' String instance...

The value of on_removal can be set later on.

h.on_removal = :destroy
h.on_removal = lambda { |val| bodycount += 1 if val.is_a?(Martian) }

auto_squeeze and on_removal were originally contributed by Gleb Kuzmenko.



mailing list

On the rufus-ruby list:

issue tracker

irc #ruote


git clone git://


John Mettraux,,

contributors and help

see CREDITS.txt



Cookies help us deliver our services. By using our services, you agree to our use of cookies Learn more