Feature #12461

Hash & keys to make subset.

Added by ioquatix (Samuel Williams) almost 2 years ago. Updated over 1 year ago.

Target version:


It would be nice if Hash had a way to create a sub-hash with a limited set of keys. This would be useful for keyword functions in particular, because sometimes you have a large hash of things and you only want to send a subset to another function.

A definition somewhat like:

class Hash
    def &(keys)
        keys.each_with_object( {|key, hash| hash[key] = self[key] if has_key?(key)}

You can see some similar definitions here:

It might be nice to support slice and slice! in a similar logical sense to Array rather than proposed & operator above - that would just be nice shortcut.

Related issues

Related to Ruby trunk - Feature #8499: Importing Hash#slice, Hash#slice!, Hash#except, and Hash#except! from ActiveSupportClosed


#1 [ruby-core:75852] Updated by ioquatix (Samuel Williams) almost 2 years ago

Just to add to this, I also found an implementation here:

Now I wonder if this warrants being in the standard library. I believe it probably does since it appears lots of people are using it, and it would probably be significantly faster written in C.

#2 Updated by shyouhei (Shyouhei Urabe) almost 2 years ago

  • Related to Feature #8499: Importing Hash#slice, Hash#slice!, Hash#except, and Hash#except! from ActiveSupport added

#3 [ruby-core:76423] Updated by matz (Yukihiro Matsumoto) almost 2 years ago

  • Status changed from Open to Closed

I am against having Hash#&. Array#& takes two arrays. The proposed Hash#& takes a hash and key array.
if you want Hash#slice to be added to the core, submit a new issue. But note that now we have real
keyword arguments so that we have less need for manipulating keyword hashes explicitly.


#4 [ruby-core:76720] Updated by usa (Usaku NAKAMURA) over 1 year ago

  • Status changed from Closed to Rejected
  • Tracker changed from Bug to Feature

Also available in: Atom PDF