What is the meaning of grep on a hash?

{'a' => 'b'}.grep /a/ => [] >> {'a' => 'b'}.grep /b/ => [] 

It does not seem to match keys or values. Does he do something that I don't understand?

+7
ruby
source share
1 answer

grep defined on Enumerable , that is, it is a generic method that knows nothing about Hash es. It works on all Enumerable elements. Ruby is not 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 items. And no matter how

 /a/ === ['a', 'b'] 

neither

 /b/ === ['a', 'b'] 

are true, you always get an empty array as an answer.

Try the following:

 def (t = Object.new).===(other) true end {'a' => 'b'}.grep t # => [['a', 'b']] 

Here you can see how grep works with Hash es.

+11
source share

All Articles