An ObjectSpace::WeakMap is a key-value map that holds weak references to its keys and values, so they can be garbage-collected when there are no more references left.

Keys in the map are compared by identity.

m = ObjectSpace::WeekMap.new
key1 = "foo"
val1 = Object.new
m[key1] = val1

key2 = "foo"
val2 = Object.new
m[key2] = val2

m[key1] #=> #<Object:0x0...>
m[key2] #=> #<Object:0x0...>

val1 = nil # remove the other reference to value
GC.start

m[key1] #=> nil
m.keys #=> ["bar"]

key2 = nil # remove the other reference to key
GC.start

m[key2] #=> nil
m.keys #=> []

(Note that GC.start is used here only for demonstrational purposes and might not always lead to demonstrated results.)

See also ObjectSpace::WeakKeyMap map class, which compares keys by value, and holds weak references only to the keys.

Instance Methods

Returns the value associated with the given key if found.

If key is not found, returns nil.

Associates the given value with the given key.

If the given key exists, replaces its value with the given value; the ordering is not affected.

Deletes the entry for the given key and returns its associated value.

If no block is given and key is found, deletes the entry and returns the associated value:

m = ObjectSpace::WeakMap.new
key = "foo"
m[key] = 1
m.delete(key) # => 1
m[key] # => nil

If no block is given and key is not found, returns nil.

If a block is given and key is found, ignores the block, deletes the entry, and returns the associated value:

m = ObjectSpace::WeakMap.new
key = "foo"
m[key] = 2
m.delete(key) { |key| raise 'Will never happen'} # => 2

If a block is given and key is not found, yields the key to the block and returns the block’s return value:

m = ObjectSpace::WeakMap.new
m.delete("nosuch") { |key| "Key #{key} not found" } # => "Key nosuch not found"

Iterates over keys and values. Note that unlike other collections, each without block isn’t supported.

Iterates over keys. Note that unlike other collections, each_key without block isn’t supported.

An alias for each

Iterates over values. Note that unlike other collections, each_value without block isn’t supported.

Returns true if key is a key in self, otherwise false.

No documentation available

Returns a new Array containing all keys in the map.

An alias for size
An alias for include?

Returns the number of referenced objects

Returns a new Array containing all values in the map.