Feature #8229

extend Hash.include?

Added by Eike Dierks about 1 year ago. Updated 10 months ago.

[ruby-core:54067]
Status:Open
Priority:Normal
Assignee:Yukihiro Matsumoto
Category:core
Target version:Next Major

Description

I'd like to suggest to extend the Hash.include? method.

Currently Hash.include? can only be used to ask for a key,
I believe it should be extended to ask for a (key value) pair.

I believe this extension can be done without breaking prior api.

I suggest to extend the signature of Hash.include?
to Hash.include?(key, value)

That message should return true,
if the receiving object does have an object at key which is equal to value.

It would be a simple replacement for:
h.include?(key) && h[key] == value

But I do not want to stop there.
I'm heading for h.includeall?(otherhash)
and h.includeany?(otherhash)

and it would be valuable to have h.intersect(other_hash) etc

I believe these to be useful primitives when working with hashes.

I'd like to have the api of the Set class available for the Hash class as well,
but there working on key/value matching.

Obviously any change to such the substantial class as the Hash class
needs a lot of thought for compatibility.

But I believe this can be done without breaking any prior code,
and it could add a lot of new out of the box functionality.

This probably needs some more thought.
We might come up with some dsl like thing like
h.includes.any? or h.includes.all? or h.includes.none?
to be used cross all collection classes.

Someone must be in charge for the Hash class,
my 2p

0001-hash.c-Hash-include-improve.patch Magnifier (5.37 KB) Nobuyoshi Nakada, 04/09/2013 04:37 PM

History

#1 Updated by Yui NARUSE about 1 year ago

  • Description updated (diff)
  • Category changed from misc to core
  • Assignee changed from Nobuyoshi Nakada to Yukihiro Matsumoto

#2 Updated by Nobuyoshi Nakada about 1 year ago

One ticket, one feature, please.

#3 Updated by Marc-Andre Lafortune about 1 year ago

Could you elaborate on why this is needed and in which cases one would need this?

Moreover, I would not write h.include?(key) && h[key] == value. In most cases h[key] == value is sufficient (unless value can be nil or there's a default proc). Otherwise one can write h.fetch(key, DIFFERENT) == value, where DIFFERENT is an value different from all possible values of the hash, like Object.new).

#4 Updated by Charles Nutter about 1 year ago

As a feature that affects all Ruby implementations, this should probably move to CommonRuby: https://bugs.ruby-lang.org/projects/common-ruby

#5 Updated by Fuad Saud 10 months ago

I think this would be more interesting if in the form:

h = { a: 'b', c: { d: 'e' } }

h.include?({c: { d: 'e' } }) # => true

It would accept a hash and check whether h includes that hash.

Also available in: Atom PDF