End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
Hash#slice
hash.slice(*keys) → new_hash
hash.c
View on GitHub ↗
static VALUE
rb_hash_slice(int argc, VALUE *argv, VALUE hash)
{
int i;
VALUE key, value, result;
if (argc == 0 || RHASH_EMPTY_P(hash)) {
return copy_compare_by_id(rb_hash_new(), hash);
}
result = copy_compare_by_id(rb_hash_new_with_size(argc), hash);
for (i = 0; i < argc; i++) {
key = argv[i];
value = rb_hash_lookup2(hash, key, Qundef);
if (!UNDEF_P(value))
rb_hash_aset(result, key, value);
}
return result;
}
Returns a new Hash object containing the entries for the given keys:
Example
h = {foo: 0, bar: 1, baz: 2} h.slice(:baz, :foo) # => {:baz=>2, :foo=>0}
Any given keys that are not found are ignored.