On Jan 23, 2006, at 10:17 AM, James Edward Gray II wrote:

> I need a Hash-like structure, using WeakRef, so that the key value  
> pairs can be garbage collected as needed.  I only need to support [] 
> () and []=(), not the whole range of Hash functions.  If the pair  
> has been collected, I just need a simple nil returned.
>
> I've tried implementing this a couple of different ways, but keep  
> running into trouble.  Does anyone have any tips?

The following code, adapted from an old post by Guy Decoux seems to  
do the trick:

class WeakCache
    def initialize( cache = Hash.new )
       @cache = cache
    end

    def []( key )
       value_id = @cache[key]
       return ObjectSpace._id2ref(value_id) unless value_id.nil?
       nil
    end

    def []=( key, value )
       ObjectSpace.define_finalizer(value, lambda { @cache.delete 
(key) })
       @cache[key] = value.object_id
    end
end

__END__

I'm still interested in seeing a WeakRefHash though, if anyone has  
rolled something similar in the past...

James Edward Gray II