15 - searching a hash with regular expressions.rb
来自「O Reilly Ruby Cookbook source code」· RB 代码 · 共 27 行
RB
27 行
h = { "apple tree" => "plant", "ficus" => "plant", "shrew" => "animal", "plesiosaur" => "animal" }h.keys.grep /p/ # => ["apple tree", "plesiosaur"]#---h.inject([]) { |res, kv| res << kv if kv[1] =~ /p/; res }# => [["ficus", "plant"], ["apple tree", "plant"]]#---class Hash def grep(pattern) inject([]) do |res, kv| res << kv if kv[0] =~ pattern or kv[1] =~ pattern res end endendh.grep(/pl/) # => [["ficus", "plant"], ["apple tree", "plant"], ["plesiosaur", "animal"]]h.grep(/plant/) # => [["ficus", "plant"], ["apple tree", "plant"]]h.grep(/i.*u/) # => [["ficus", "plant"], ["plesiosaur", "animal"]]#---res = []h.each_key { |k| res << k if k =~ /p/ }res # => ["apple tree", "plesiosaur"]#---
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?