Grep a hash : Hash Extensions « Hash « Ruby






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"]]

 








Related examples in the same category

1.Add method to Hash class to remove one hash from another
2.Add method hash class to invert a hash: turn value to key
3.Find all