我知道三重循环的想法给一些人的思想带来了恐惧,但我有一个具有以下结构的代码:
paragraph.split(/(\.|\?|\!)[\s\Z]/).each do |sentence|
myArrayOfFiles.each_with_index { |ma,j|
ma.each_with_index { |word,i|
sentence.gsub!(...)
}
}
end
两个外部循环按预期运行,但由于某种原因,内部循环仅在第一个sentence
上运行。你知道为什么吗?如何让内循环遍及所有sentence
s呢?
我在Ruby 1.8.7上运行,并且仅使用each
循环尝试了相同的代码,并得到了相同的结果。有任何想法吗?
编辑:
myArrayOfFiles
是一个数组填充:
AFile = File.open("A.txt")
BFile = File.open("B.txt")
myArrayOfFiles << [Afile,BFile]
myArrayOfFiles.flatten!
您的问题是myArrayOfFiles
包含文件实例。当您使用ma.each_with_index
迭代其中一个文件时,它将逐行浏览文件并停在EOF处。然后,你尝试再次使用下一个sentence
迭代,但文件已经在EOF,所以ma.each_with_index
没有任何东西可以迭代,没有任何有趣的事情发生。在尝试再次使用rewind
之前,需要调用each_with_index
将文件移回到开头:
paragraph.split(/(\.|\?|\!)[\s\Z]/).each do |sentence|
myArrayOfFiles.each_with_index do |ma, j|
ma.rewind # <------------------------- You need this
ma.each_with_index do |word, i|
sentence.gsub!(...)
end
end
end