LRUHash
An LRUHash holds a fixed number of entries. When it's full, adding one drops the entry that was used least recently. pdf-reader uses it to cache the objects it reads from a PDF.
require 'hashery/lru_hash'
cache = Hashery::LRUHash.new(2)
cache[:a] = 1
cache[:b] = 2
cache[:a] # reading :a makes it the most recently used
cache[:c] = 3 # full, so :b is dropped
cache.keys # => [:c, :a]
cache.fetch(:b, 0) # => 0
Reading an entry with [], fetch and the like
counts as using it; checking for a key or iterating doesn't. Set
release_proc to hear about each entry that leaves. An LRUHash
isn't thread-safe, so guard it with a Mutex if threads share it.
Dictionary
A Dictionary keeps its entries in order, with array-like methods to match, and can keep itself sorted by key or by value as entries are added.
require 'hashery/dictionary'
fruit = Hashery::Dictionary.new.order_by_key
fruit[:pear] = 3
fruit[:apple] = 5
fruit[:fig] = 1
fruit.keys # => [:apple, :fig, :pear]
All the classes
Each class is documented in its source file, and the demos show most of them at work.
Caches and ordering
- LRUHash
- A Hash of limited size that drops the least recently used entry.
- Dictionary
- An ordered Hash that can keep itself sorted by key or value.
- LinkedList
- A doubly linked list whose elements can be looked up by key.
- OrderedHash
- An insertion-ordered Hash, from before Ruby's own Hash kept order.
Keys you can call
- OpenHash
- A Hash whose keys also work as methods, like OpenStruct.
- OpenCascade
- An OpenHash that does the same for the hashes inside it, so
config.db.hostworks. - QueryHash
- A Hash whose keys are read with
?and!methods, such asq.name?.
Control over keys and values
- KeyHash
- A Hash that passes every key through a block, to normalize it. Stash is its old name.
- CastingHash
- A Hash that passes keys and values through procs of your own.
- PropertyHash
- A Hash that accepts only the keys it was given at the start.
- StaticHash
- A Hash that raises an error when a key is set a second time.
- FuzzyHash
- A Hash whose keys can be regular expressions that match on lookup.
- PathHash
- A nested Hash you can also reach into with keys like
"a/b". - CRUDHash
- A Hash built on a handful of core methods, for subclassing.
And also
- IniHash
- A Hash that reads and writes INI files.
- Association
- A pair of objects, written
:apple >> :fruit.
require 'hashery' also adds a
few methods to Ruby's Hash: rekey, rekey!,
retrieve and Hash.create.
}