论坛首页 编程语言技术论坛

根据正则匹配hash

浏览 2479 次
精华帖 (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"]]

 

   发表时间: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"}



0 请登录后投票
论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics