How to use Enumerable#grep with Hash object/collection

I used #grep method with Range,Array.

a = [‘foo’,‘fish’,‘bar’]
a.grep(/f/) # => [“foo”, “fish”]
(1…40).grep (6…9) # => [6, 7, 8, 9]

But never with Hash. So today I tried something like below :

h = { “arup” => 100, “banti” => 200, “carry” => 300, “Pood” => 300 }
h.grep(/a/i) # => []

Intention was to collect all key/value which has key, that match a
pattern /a/i. But it didn’t worked. With Hash, probably #grep not worked
that way.

Any one can tell me how to use #grep with a Enumerable like Hash ?

On 2014-Mar-12, at 14:50 , Arup R. [email protected] wrote:

Intention was to collect all key/value which has key, that match a
pattern /a/i. But it didn’t worked. With Hash, probably #grep not worked
that way.

Any one can tell me how to use #grep with a Enumerable like Hash ?


Posted via http://www.ruby-forum.com/.

Well, according to http://apidock.com/ruby/v1_9_3_392/Enumerable/grep

grep(p1) public

Returns an array of every element in enum for which Pattern === element.
If the optional block is supplied, each matching element is passed to
it, and the blocks result is stored in the output array.

And the elements come from #each, which is Hash#each in this case, so
http://apidock.com/ruby/v1_9_3_392/Hash/each

Since that passes the key-value pair, let’s see what that looks like:

irb2.1.0> h = { “arup” => 100, “banti” => 200, “carry” => 300, “Pood” =>
300 }
#2.1.0 => {“arup”=>100, “banti”=>200, “carry”=>300, “Pood”=>300}
irb2.1.0> h.each {|element| p element}
[“arup”, 100]
[“banti”, 200]
[“carry”, 300]
[“Pood”, 300]
#2.1.0 => {“arup”=>100, “banti”=>200, “carry”=>300, “Pood”=>300}

So #grep is doing:

/a/i === [“arup”, 100]

I wonder what Regexp#=== does?
http://apidock.com/ruby/v1_9_3_392/Regexp/%3D%3D%3D

===(p1) public
Case EqualitySynonym for Regexp#=~ used in case statements.

OK, http://apidock.com/ruby/Regexp/%3D~

But, let’s look at what the Pickaxe has to say:

Case EqualityLike Regexp#=~ but accepts nonstring arguments (returning
false). Used in case statements.

Ah-HA! Since [“arup”,100] is a nonstring argument, so it would return
false.

Perhaps you want to do something like:

irb2.1.0> h.select {|k,v| /a/i =~ k}
#2.1.0 => {“arup”=>100, “banti”=>200, “carry”=>300}

-Rob

Rob B. wrote in post #1139632:

On 2014-Mar-12, at 14:50 , Arup R. [email protected] wrote:

Perhaps you want to do something like:

irb2.1.0> h.select {|k,v| /a/i =~ k}
#2.1.0 => {“arup”=>100, “banti”=>200, “carry”=>300}

-Rob

Thank you very much.

I am actually looking for any use cases are there or not to use #grep
with Hash, like others. Documentation didn’t have any example with Hash.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs