Ruby grep与行号 [英] Ruby grep with line number
本文介绍了Ruby grep与行号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用Ruby的 Enumerable#grep
方法获取匹配行与行号的最佳方式是什么? (因为我们使用 -n
或 - line-number
使用grep命令切换)。
What could be the best way of getting the matching lines with the line numbers using Ruby's Enumerable#grep
method. (as we use -n
or --line-number
switch with grep command).
推荐答案
Enumerable#grep不会让你这样做,至少在默认情况下。相反,我想出了:
Enumerable#grep doesn't let you do that, at least by default. Instead, I came up with:
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]]
这篇关于Ruby grep与行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文