📄 15 - searching a hash with regular expressions.rb
字号:
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 + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -