三循环Ruby

问题描述 投票:2回答:1

我知道三重循环的想法给一些人的思想带来了恐惧,但我有一个具有以下结构的代码:

paragraph.split(/(\.|\?|\!)[\s\Z]/).each do |sentence|
    myArrayOfFiles.each_with_index { |ma,j|
        ma.each_with_index { |word,i|
            sentence.gsub!(...)
        }
    }
end

两个外部循环按预期运行,但由于某种原因,内部循环仅在第一个sentence上运行。你知道为什么吗?如何让内循环遍及所有sentences呢?

我在Ruby 1.8.7上运行,并且仅使用each循环尝试了相同的代码,并得到了相同的结果。有任何想法吗?

编辑:

myArrayOfFiles是一个数组填充:

AFile = File.open("A.txt")
BFile = File.open("B.txt")
myArrayOfFiles << [Afile,BFile]
myArrayOfFiles.flatten!
ruby file loops each
1个回答
7
投票

您的问题是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
© www.soinside.com 2019 - 2024. All rights reserved.