Project

General

Profile

Actions

Feature #12461

closed

Hash & keys to make subset.

Feature #12461: Hash & keys to make subset.

Added by ioquatix (Samuel Williams) almost 10 years ago. Updated over 9 years ago.

Status:
Rejected
Assignee:
-
Target version:
-
[ruby-core:75851]

Description

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(self.class.new) {|key, hash| hash[key] = self[key] if has_key?(key)}
    end
end

You can see some similar definitions here: https://github.com/rails/rails/blob/b670fadb978c8a12c3414ed842cd49e4fde2cec0/activesupport/lib/active_support/core_ext/hash/slice.rb#L21

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 1 (0 open1 closed)

Related to Ruby - Feature #8499: Importing Hash#slice, Hash#slice!, Hash#except, and Hash#except! from ActiveSupportClosedmatz (Yukihiro Matsumoto)Actions

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

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

https://github.com/rubyworks/facets/blob/master/lib/core/facets/hash/slice.rb

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.

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

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

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

  • 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.

Matz.

Updated by usa (Usaku NAKAMURA) over 9 years ago Actions #4 [ruby-core:76720]

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

Also available in: PDF Atom