Ruby grep与行号

int*_*iot 10 ruby grep

使用Ruby 方法获取匹配行与行号的最佳方法是什么?Enumerable#grep(因为我们使用-n--line-number使用grep命令切换).

the*_*Man 8

可枚举#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)


J-_*_*_-L 7

也许是这样的:

module Enumerable
  def lgrep(pattern)
    map.with_index.select{|e,| e =~ pattern}
  end
end
Run Code Online (Sandbox Code Playgroud)