Ruby grep with line number Ruby grep with line number ruby ruby

Ruby grep with line number


Enumerable#grep doesn't let you do that, at least by default. Instead, I came up with:

text = 'now is the timefor all good mento come to the aidof 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]]


maybe something like this:

module Enumerable  def lgrep(pattern)    map.with_index.select{|e,| e =~ pattern}  endend


This isn't elegant or efficient, but why not just number the lines before grepping?