Class: Ferret::Utils::WeakKeyHash
- Inherits:
-
Monitor
- Object
- Monitor
- Ferret::Utils::WeakKeyHash
- Defined in:
- lib/ferret/utils/weak_key_hash.rb
Overview
This class implements a weak key hash. ie all keys that are stored in this hash can still be garbage collected, and if they are garbage collected then the key and it’s corresponding value will be deleted from the hash.
eg.
name = "david"
last_names = WeakKeyHash.new()
last_names[name] = "balmain"
puts last_names["david"] #=>"balmain"
GC.start
puts last_names["david"] #=>"balmain"
name = nil
GC.start
# the name "david" will now have been garbage collected so it should
# have been removed from the hash
puts last_names["david"] #=>nil
WeakKeyHash subclasses Monitor so it can be synchronized on.
NOTE
Unfortunately the ruby garbage collector is not always predictable so your results may differ but each key should eventually be freed when all other references have been removed and the garbage collector is ready.
Instance Method Summary collapse
-
#[](key) ⇒ Object
Get the value for the key.
-
#[]=(key, value) ⇒ Object
Set the value for the key just like a Hash.
-
#initialize ⇒ WeakKeyHash
constructor
Create a new WeakKeyHash.
-
#size ⇒ Object
Return the number of elements in the Hash.
-
#to_s ⇒ Object
Print a string representation the WeakKeyHash.
Constructor Details
#initialize ⇒ WeakKeyHash
Create a new WeakKeyHash.
30 31 32 33 34 |
# File 'lib/ferret/utils/weak_key_hash.rb', line 30 def initialize super() @hash = {} @deleter = lambda{|id| @hash.delete(id)} end |
Instance Method Details
#[](key) ⇒ Object
Get the value for the key
43 44 45 |
# File 'lib/ferret/utils/weak_key_hash.rb', line 43 def [](key) return @hash[key.object_id] end |
#[]=(key, value) ⇒ Object
Set the value for the key just like a Hash
37 38 39 40 |
# File 'lib/ferret/utils/weak_key_hash.rb', line 37 def []=(key, value) ObjectSpace.define_finalizer(key, @deleter) @hash[key.object_id] = value end |
#size ⇒ Object
Return the number of elements in the Hash
48 49 50 |
# File 'lib/ferret/utils/weak_key_hash.rb', line 48 def size @hash.size end |
#to_s ⇒ Object
Print a string representation the WeakKeyHash
53 54 55 56 57 |
# File 'lib/ferret/utils/weak_key_hash.rb', line 53 def to_s buffer = "" @hash.each_pair {|key, value| buffer << "<#{ObjectSpace._id2ref(key)}=>#{value}>"} return buffer end |