files = ["message_21.txt", "message_10.txt", "message_27.txt", "message_22.txt", "message_23.txt", "message_15.txt", "message_4.txt", "message_16.txt", "message_24.txt", "message_13.txt", "message_1.txt", "message_3.txt", "message_17.txt", "message_12.txt", "message_2.txt", "message_19.txt", "message_18.txt", "message_14.txt", "message_25.txt", "message_9.txt", "message_8.txt", "message_5.txt", "message_26.txt", "message_11.txt", "message_7.txt", "message_20.txt", "message_6.txt", "message_28.txt"]
files.each do |f|
file = File.new(PATH + "/" + f, "r")
while (line = file.gets)
@found=true if line =~ /You purchased/
next unless @found
puts line
exit if line =~ /Order for/
end
file.close
end
如果message_4.txt包含'您购买'且'订单'字词完全退出循环。所以我无法获得包含这些术语的其他文件。我不知道我做了什么错误。
答案 0 :(得分:1)
一旦达到'订购',您是否试图突破while循环?因为'退出'不是你想要的。试试'休息'吧。此外,您还需要为每个文件重置@found变量。
files = ["message_21.txt", "message_10.txt", "message_27.txt", "message_22.txt", "message_23.txt", "message_15.txt", "message_4.txt", "message_16.txt", "message_24.txt", "message_13.txt", "message_1.txt", "message_3.txt", "message_17.txt", "message_12.txt", "message_2.txt", "message_19.txt", "message_18.txt", "message_14.txt", "message_25.txt", "message_9.txt", "message_8.txt", "message_5.txt", "message_26.txt", "message_11.txt", "message_7.txt", "message_20.txt", "message_6.txt", "message_28.txt"]
files.each do |f|
@found = false
file = File.new(PATH + "/" + f, "r")
while (line = file.gets)
@found=true if line =~ /You purchased/
# below skips to start of next run of while loop
next unless @found
puts line
# below breaks out of while loop
break if line =~ /Order for/
end
file.close
end
看看这个http://www.tutorialspoint.com/ruby/ruby_loops.htm - 尤其是“下一个”和“休息”的解释。
答案 1 :(得分:0)
exit
退出整个程序,而不仅仅是循环。您需要break
,而不是exit
来停止循环。
您还可以利用File.open
接受一个块,该块会在块返回时为您关闭文件。
除非您有意存储至少在一个文件中找到@found
行至少一次,否则也不需要You purchased
。
最后,你应该修复你的缩进,每个级别使用两个空格,这是Ruby社区中公认的标准。
files = [...]
files.each do |f|
File.open(PATH + "/" + f, "r") do |file|
while line = file.gets
next unless line =~ /You purchased/
puts line
break if line =~ /Order for/
end
end
end