获得匹配线的最佳方法是什么与行号使用 Ruby 的Enumerable#grep
方法。 (当我们使用-n
or --line-number
使用 grep 命令切换)。
Enumerable#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]]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)