我有两个文件file1.txt
和file2.txt
file1.txt
内容:
line 1 file 1
line 2 file 1
line 3 file 1
file2.txt
内容:
line 1 file 2
line 2 file 2
line 3 file 2
并拥有以下ruby
代码:
nin_file = File.open "file1.txt"
dev_id_file = File.open "file2.txt"
nin_file.each do |nin_line|
dev_id_file.each do |dev_line|
nin_line.delete!("\r\n")
puts "#{nin_line} => #{dev_line}"
end
end
nin_file.close
dev_id_file.close
(1..3).each do |e1|
(1..5).each do |e2|
puts "#{e1} => #{e2}"
end
end
这是输出(为什么内部每个都不能处理文件,但适用于范围!)
line 1 file 1 => line 1 file 2
line 1 file 1 => line 2 file 2
line 1 file 1 => line 3 file 2
1 => 1
1 => 2
1 => 3
1 => 4
1 => 5
2 => 1
2 => 2
2 => 3
2 => 4
2 => 5
3 => 1
3 => 2
3 => 3
3 => 4
3 => 5
答案 0 :(得分:1)
nin_file.each
的第一次迭代后,dev_id_file
的流为空:
dev_id_file.each do |dev_line|
puts "1 => #{dev_line}"
end
dev_id_file.each do |dev_line|
puts "2 => #{dev_line}"
end
输出:
1 => line 1 file 2
1 => line 2 file 2
1 => line 3 file 2
要让它每次都有效,你需要在数组上完成它:
nin_file = File.readlines"file1.txt"
dev_id_file = File.readlines "file2.txt"
nin_file.each do |nin_line|
dev_id_file.each do |dev_line|
nin_line.delete!("\r\n")
puts "#{nin_line} => #{dev_line}"
end
end
输出:
line 1 file 1 => line 1 file 2
line 1 file 1 => line 2 file 2
line 1 file 1 => line 3 file 2
line 2 file 1 => line 1 file 2
line 2 file 1 => line 2 file 2
line 2 file 1 => line 3 file 2
line 3 file 1 => line 1 file 2
line 3 file 1 => line 2 file 2
line 3 file 1 => line 3 file 2
答案 1 :(得分:0)
file2
。这就是为什么你没有看到任何进一步的路线。
这应该可以提供您想要的输出。
nin_file = File.open "file1.txt"
dev_id_file = File.open "file2.txt"
nin_file.each do |nin_line|
dev_id_file.rewind
dev_id_file.each do |dev_line|
nin_line.delete!("\r\n")
puts "#{nin_line} => #{dev_line}"
end
end