我想读取两个文本文件,并同时处理它们,如下所示:
f1 = File.open(...)
f2 = File.open(...)
|f1, f2|.each do |l1,l2|
......
end
Run Code Online (Sandbox Code Playgroud)
我怎么能在Ruby中做到这一点?
如何避免与matt的答案相关的记忆吮吸:
f1 = File.open(...)
f2 = File.open(...)
f1.each.zip(f2.each).each do |line1, line2|
# Do something with the lines
end
Run Code Online (Sandbox Code Playgroud)
zip 是Enumerable中许多鲜为人知的方法之一,值得了解,特别是如果你对学习函数式编程范式感兴趣的话.
它避免了与matt的答案相关的内存吮吸,因为它不是读取所有内容,而是f1.each返回一个只能在需要时使用的枚举器.