Skip to content

Instantly share code, notes, and snippets.

@rkh
Created May 20, 2013 11:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rkh/5611706 to your computer and use it in GitHub Desktop.
Save rkh/5611706 to your computer and use it in GitHub Desktop.
class EqualityMap
def initialize
@keys = {}
@map = ObjectSpace::WeakMap.new
end
def fetch(*key)
identity = @keys[key.hash]
key = identity == key ? identity : key
@map[key] ||= track(key, yield)
end
def track(key, object)
ObjectSpace.define_finalizer(object, finalizer(hash))
@keys[key.hash] = key
object
end
def finalizer(hash)
proc { @keys.delete(hash) }
end
private :track, :finalizer
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment