{'a' => 'b'}.grep /a/
=> []
>> {'a' => 'b'}.grep /b/
=> []
It doesn't seem to match the keys or values. Does it do something I'm not discerning?
grep
is defined on Enumerable
, i.e. it is a generic method that doesn't know anything about Hash
es. It operates on whatever the elements of the Enumerable
are. Ruby doesn't have a type for key-value-pairs, it simply represents Hash
entries as two-element arrays where the first element is the key and the second element is the value.
grep
uses the ===
method to filter out elements. And since neither
/a/ === ['a', 'b']
nor
/b/ === ['a', 'b']
are true, you always get an empty array as response.
Try this:
def (t = Object.new).===(other)
true
end
{'a' => 'b'}.grep t
# => [['a', 'b']]
Here you can see how grep
works with Hash
es.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With