Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →
instance method
Hash#compact!
hash.compact! → self or nil
hash.c
View on GitHub ↗
static VALUE
rb_hash_compact_bang(VALUE hash)
{
st_index_t n;
rb_hash_modify_check(hash);
n = RHASH_SIZE(hash);
if (n) {
rb_hash_foreach(hash, delete_if_nil, hash);
if (n != RHASH_SIZE(hash))
return hash;
}
return Qnil;
}
Returns self with all its nil-valued entries removed (in place):
Example
h = {foo: 0, bar: nil, baz: 2, bat: nil} h.compact! # => {:foo=>0, :baz=>2}
Returns nil if no entries were removed.
See also
#compact
#compare_by_identity
#clear
#compare_by_identity?
also in
4.1 · 4.0 · 3.4 · 3.2 · 3.1 · 3.0