gpt4 book ai didi

Ruby:逐行匹配范围

转载 作者:太空宇宙 更新时间:2023-11-03 17:24:29 26 4
gpt4 key购买 nike

有没有办法在 Ruby 中实现以下 Perl 结构?

while( my $line = $file->each_line() ) {
if($line =~ /first_line/ .. /end_line_I_care_about/) {
do_something;
# this will do something on a line per line basis on the range of the match
}
}

在 ruby​​ 中,它的内容如下:

file.each_line do |line|
if line.match(/first_line/) .. line.match(/end_line_I_care_about/)
do_something;
# this will only do it based on the first match not the range.
end
end

将整个文件读入内存不是一种选择,我不知道范围的 block 有多大。

编辑:

感谢您的回答,我得到的答案与我最初的代码基本相同。我遇到的问题是“它可以测试正确的操作数并在相同的评估中变为假(如在 awk 中),但它仍然返回一次真。”

“如果您不希望它在下一次评估之前测试正确的操作数,就像在 sed 中一样,只需使用三个点(“...”)而不是两个。在所有其他方面,“...”行为就像“..”一样。”

我将正确答案标记为指出“..”可以在发出同一个调用时关闭的答案。

作为引用,我使用的代码是:

file.each_line do |line|
if line.match(/first_line/) ... line.match(/end_line_I_care_about/)
do_something;
end
end

最佳答案

是的,Ruby 支持触发器:

str = "aaa
ON
bbb
OFF
cccc
ON
ddd
OFF
eee"
str.each_line do |line|
puts line if line =~ /ON/..line =~ /OFF/
#puts line if line.match(/ON/)..line.match(/OFF/) #works too
end

输出:

ON
bbb
OFF
ON
ddd
OFF

关于Ruby:逐行匹配范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17457440/

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