class ObjectSpace::WeakMap

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::WeakMap.new
key1 = "foo"
val1 = Object.new
m[key1] = val1

key2 = "bar"
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.