tags:

views:

47

answers:

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

+3  A: 

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.

Jörg W Mittag
Thanks, I see that === is defined for Object, but not overridden for Hash, so it's not really meaningful. But at least I see now that: {'a' => 'b'}.grep Array ... => [["a", "b"]]
@user258980: The fact that `Hash#===` is not defined is completely irrelevant, since you are not calling `Hash#===`, you are calling `Hash#grep`. `Hash#grep` then calls the `===` method of whatever object was passed into it. In your example, that object is `/a/`, so `Hash#grep` ends up calling `Regexp#===` passing each element in turn. Since those elements are two-element arrays, and a `Regexp` obviously never can match an array, only strings, the result will always be empty.
Jörg W Mittag
Thanks for clarifying.