浏览 2479 次
锁定老帖子 主题:根据正则匹配hash
精华帖 (0) :: 良好帖 (0) :: 新手帖 (9) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2009-12-24
首先写个方法。
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/) # => [["ficus", "plant"], ["apple tree", "plant"], ["plesiosaur", "animal"]] p h.grep(/plant/) # => [["ficus", "plant"], ["apple tree", "plant"]] p h.grep(/i.*u/) # => [["ficus", "plant"], ["plesiosaur", "animal"]]
声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |
发表时间:2009-12-24
居然返回了数组。。。
楼主这样一点意义也没有.. class Hash def key_scan pattern Hash[*select{|k, _| k =~ pattern}.flatten] end def value_scan pattern Hash[*select{|_, v| v =~ pattern}.flatten] end end h = { "apple tree" => "plant", "ficus" => "plant", "shrew" => "animal", "plesiosaur" => "animal" } p h.key_scan(/pl/) #{"apple tree"=>"plant", "plesiosaur"=>"animal"} p h.value_scan(/pl/) #{"apple tree"=>"plant", "ficus"=>"plant"} |
|
返回顶楼 | |