Skip to content

Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →

instance method

ObjectSpace::WeakKeyMap#getkey

(untyped) -> Key?
map.getkey(key) → existing_key or nil

Returns the existing equal key if it exists, otherwise returns nil.

This might be useful for implementing caches, so that only one copy of some object would be used everywhere in the program:

Example
value = {amount: 1, currency: 'USD'}

# Now if we put this object in a cache:
cache = ObjectSpace::WeakKeyMap.new
cache[value] = true

# ...we can always extract from there and use the same object:
copy = cache.getkey({amount: 1, currency: 'USD'})
copy.object_id == value.object_id #=> true
See also #delete #inspect #clear #key? also in 4.1 · 4.0 · 3.3