Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →
instance method
ObjectSpace::WeakKeyMap#getkey
map.getkey(key) → existing_key or nil
weakmap.c
View on GitHub ↗
static VALUE
wkmap_getkey(VALUE self, VALUE key)
{
struct weakkeymap *w;
TypedData_Get_Struct(self, struct weakkeymap, &weakkeymap_type, w);
st_data_t orig_key;
if (!st_get_key(w->table, (st_data_t)&key, &orig_key)) return Qnil;
return *(VALUE *)orig_key;
}
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