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? Can't you just do something like this? require 'delegate' require 'weakref' WeakHash = DelegateClass(Hash) class WeakHash def []=(key,val) __getobj__[WeakRef.new(key)] = WeakRef.new(val) end def [](key) __getobj__[WeakRef.new(key)] end def each(&b) __getobj__.each do |k,v| b[k.__getobj__, v.__getobj__] unless k.__getobj__.nil? end self end def cleanup delete_if {|k,v| k.__getobj__.nil?} end end Kind regards robert