开发者

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜