Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of grep on a Hash?

Tags:

ruby

{'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?

like image 547
user258980 Avatar asked Sep 16 '10 03:09

user258980


1 Answers

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.

like image 154
Jörg W Mittag Avatar answered Nov 05 '22 19:11

Jörg W Mittag