Class: SimpleWeakHash

Inherits:
Object
  • Object
show all
Defined in:
lib/simple_weak_hash.rb

Overview

SimpleWeakHash is a weak hash with more relaxed semantics than a WeakHash:

  • the key->value associations can disappear at any time

  • all existent associations are wiped out when the GC kicks in

In particular, it removes the tacit requirement that an association remain alive as long as there is an external reference (i.e. outside the hash) to either the key or the value. The advantage is increased speed.

Instance Method Summary collapse

Constructor Details

#initializeSimpleWeakHash

Returns a new instance of SimpleWeakHash.



17
18
19
20
# File 'lib/simple_weak_hash.rb', line 17

def initialize
  @valid = false
  @mutex = Mutex.new
end

Instance Method Details

#[](key) ⇒ Object

retrieve object with the given key returns the object if present and it has not been garbage collected. Otherwise it returns nil.



25
26
27
# File 'lib/simple_weak_hash.rb', line 25

def [](key)
  __get_hash__[key]
end

#[]=(key, value) ⇒ Object

“store” object into the weak hash using the given key a weak reference is stored so the object stays references as long as it isn’t garbage collected.



32
33
34
# File 'lib/simple_weak_hash.rb', line 32

def []=(key, value)
  __get_hash__[key] = value
end

#update(hash) ⇒ Object

an addition to Mauricio’s implementation, simple method that act’s like Hash#update method.



38
39
40
41
# File 'lib/simple_weak_hash.rb', line 38

def update(hash)
  hash.each { |key, val| send(:[]=, key, val) }
  self
end