What is the meaning of grep on a Hash?
{'a' => 'b'}.grep /a/
=> []
>> {'a' => 'b'}.grep /b/
=> []
It doesn't seem to match the keys or v开发者_如何学Calues. 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.
精彩评论