Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
instance method
Hash#compact!
() -> self?
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;
}
If self contains any nil-valued entries, returns self with all nil-valued entries removed; returns nil otherwise:
Example
h = {foo: 0, bar: nil, baz: 2, bat: nil} h.compact! h # => {foo: 0, baz: 2} h.compact! # => nil
Related: see Methods for Deleting.
See also
#compact
#compare_by_identity
#clear
#compare_by_identity?
also in
4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0