No Ephemerons in Ruby's WeakMap
Let’s say you want to associate a property with an object, but you don’t want
to write to the object directly, maybe for design reasons or logistical reasons
(what if the object is frozen and immutable?) You can use WeakMap
for this,
and the garbage collector is free to collect keys of the map:
object = []
map = ObjectSpace::WeakMap.new
map[object] = [object]
p map.member?(object) # => true
There is an issue with this demo, however. Currently, Ruby’s WeakMap
doesn’t keep the values of the map alive, so the map evicts the pair in the
demo after a garbage collection run, even though the key survives: