End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
Hash#compact
hash.compact → new_hash
hash.c
View on GitHub ↗
static VALUE
rb_hash_compact(VALUE hash)
{
VALUE result = rb_hash_new();
if (!RHASH_EMPTY_P(hash)) {
rb_hash_foreach(hash, set_if_not_nil, result);
}
return result;
}
Returns a copy of self with all nil-valued entries removed:
Example
h = {foo: 0, bar: nil, baz: 2, bat: nil} h1 = h.compact h1 # => {:foo=>0, :baz=>2}