From: "zverok (Victor Shepelev)" Date: 2021-11-20T10:39:17+00:00 Subject: [ruby-core:106190] [Ruby master Misc#18352] What is the Hash#grep expected? Issue #18352 has been updated by zverok (Victor Shepelev). > This result almost make Include Enumerable#grep into Hash is totally meaningless, right? Not completely, but close to it :) As `grep` accepts anything with `#===`, we might imagine some custom useful objects passed, like, IDK.... ```ruby class HashMatcher < Struct.new(:key, :value, keyword_init: true) def ===((k, v)) (key.nil? || key === k) && (value.nil? || value === v) end end {foo1: '100', foo2: '200', bar: '200'}.grep(HashMatcher[key: /foo/]) # => [[:foo1, "100"], [:foo2, "200"]] ``` ...but that would be quite an esoteric technique (which I personally never used) But, considering more useful `Hash#grep`, I am not sure I agree with this: > Following is what is expected. (=== is matching on hash key, as Hash#slice) Why not match only hash **value**, like, say, `Hash#compact`? ```ruby {foo1: '100', foo2: '200', bar: '200'}.grep /^1/ # => {foo1: '100'} {foo1: 100, foo2: 200, bar: 200}.grep(100...150) # => {foo1: '100'} ``` I can imagine arguments towards both behaviors saying that they are "natural/useful/expected", and I don't think there is one right answer here actually. ---------------------------------------- Misc #18352: What is the Hash#grep expected? https://bugs.ruby-lang.org/issues/18352#change-94797 * Author: zw963 (Wei Zheng) * Status: Open * Priority: Normal ---------------------------------------- Current ruby implement, When use Array#grep, the method name means is expected. ``` [19] pry(#)> [:foo1, :foo2, :bar].grep /foo/ [ :foo1, :foo2 ] ``` But when use with hash, the result is really confusing ... ```rb [12] pry(#)> {foo: '100', bar: '200'}.grep /foo/ [] ``` This result almost make Include Enumerable#grep into Hash is totally meaningless, right? so, i consider if we should introduce a `Hash#grep` method instead. Following is what is expected. (=== is matching on hash key, as Hash#slice) ```rb [20] pry(#)> {foo1: '100', foo2: '200', bar: '200'}.grep /foo/ { :foo1 => "100", :foo2 => "200" } ``` -- https://bugs.ruby-lang.org/ Unsubscribe: