Mega Code Archive

 
Categories / Ruby / Hash
 

Grep a hash

class Hash   def grep(pattern)     inject([]) do |res, kv|       res << kv if kv[0] =~ pattern or kv[1] =~ pattern       res     end   end end h = { "apple tree" => "plant", "ficus" => "plant",       "shrew" => "animal", "plesiosaur" => "animal" } p h.grep(/pl/) p h.grep(/plant/)        # => [["ficus", "plant"], ["apple tree", "plant"]] p h.grep(/i.*u/)         # => [["ficus", "plant"], ["plesiosaur", "animal"]]