instance method · added in Ruby 3.3
ObjectSpace::WeakMap#delete
map.delete(key) → value or nil
map.delete(key) {|key| ... } → object
weakmap.c
View on GitHub ↗
static VALUE
wmap_delete(VALUE self, VALUE key)
{
struct weakmap *w;
TypedData_Get_Struct(self, struct weakmap, &weakmap_type, w);
VALUE orig_key = key;
st_data_t orig_key_data = (st_data_t)&orig_key;
st_data_t orig_val_data;
if (st_delete(w->table, &orig_key_data, &orig_val_data)) {
VALUE orig_val = *(VALUE *)orig_val_data;
rb_gc_remove_weak(self, (VALUE *)orig_key_data);
rb_gc_remove_weak(self, (VALUE *)orig_val_data);
struct weakmap_entry *entry = (struct weakmap_entry *)orig_key_data;
ruby_sized_xfree(entry, sizeof(struct weakmap_entry));
if (wmap_live_p(orig_val)) {
return orig_val;
}
}
if (rb_block_given_p()) {
return rb_yield(key);
}
else {
return Qnil;
}
}
Deletes the entry for the given key and returns its associated value.
If no block is given and key is found, deletes the entry and returns the associated value:
Example
m = ObjectSpace::WeakMap.new key = "foo" m[key] = 1 m.delete(key) # => 1 m[key] # => nil
If no block is given and key is not found, returns nil.
If a block is given and key is found, ignores the block, deletes the entry, and returns the associated value:
Example
m = ObjectSpace::WeakMap.new key = "foo" m[key] = 2 m.delete(key) { |key| raise 'Will never happen'} # => 2
If a block is given and key is not found, yields the key to the block and returns the block’s return value:
Example
m = ObjectSpace::WeakMap.new m.delete("nosuch") { |key| "Key #{key} not found" } # => "Key nosuch not found"
Ruby version changes
-
3.3
-
ObjectSpace::WeakMap#deletewas added to eagerly clear weak map entries. [Feature #19561]
-