gpt4 book ai didi

带有行号的 Ruby grep

转载 作者:数据小太阳 更新时间:2023-10-29 06:45:34 26 4
gpt4 key购买 nike

使用 Ruby 的 Enumerable#grep 方法获取匹配行与行号的最佳方法是什么。 (因为我们在 grep 命令中使用 -n--line-number 开关)。

最佳答案

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]]

关于带有行号的 Ruby grep,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5761348/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com