使用Ruby 方法获取匹配行与行号的最佳方法是什么?Enumerable#grep
(因为我们使用-n
或--line-number
使用grep命令切换).
可枚举#grep不允许你这样做,至少在默认情况下是这样.相反,我想出了:
text = 'now is the time
for all good men
to come to the aid
of their country'
regex = /aid/
hits = text.lines.with_index(1).inject([]) { |m,i| m << i if (i[0][regex]); m }
hits # => [["to come to the aid\n", 3]]
Run Code Online (Sandbox Code Playgroud)
也许是这样的:
module Enumerable
def lgrep(pattern)
map.with_index.select{|e,| e =~ pattern}
end
end
Run Code Online (Sandbox Code Playgroud)