I have a number of Ruby objects with unique IDs that I am currently caching in a Hash. When an object is assigned an ID, it goes into the Hash. The cache is complete, i.e. every object with an ID that exists in the Ruby scope should also be in the cache.
However, I am having trouble finding a way to delete objects from the cache once they disappear from all other scopes. This is, of course, because objects contained in the cache will not be garbage collected.
Are there any approaches to this problem? The documentation for WeakRef
suggests a WeakHash
class, but it does not seem acceptable for practical use, although it is very close to what I think I need for my project.
Something similar to WeakHash will do it. Here's a more complete implementation that can handle Fixnums, Symbols, and Floats (and other immutable types if you add them to the list):
class WeakHash < Hash
def []=(k, v)
if(![Fixnum, Symbol, Float].include? k.class)
k = WeakRef.new(k)
end
if(![Fixnum, Symbol, Float].include? v.class)
v = WeakRef.new(v)
end
super k,v
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With