Ruby在循环中写入多个文件不会给出预期的答案

Ruby在循环中写入多个文件不会给出预期的答案,ruby,Ruby,我有一些ruby代码,可以执行并创建一些带有输出的文件 当我只运行一次代码时,我一点问题都没有,但是当我尝试在循环中运行它时,第一个文件输出正常,但是从第二个文件开始,它们都遵循一种奇怪的模式 如果我运行它三次,第一个输出是正常的,第二个是第一个输出的信息,后面是它应该具有的输出,第三个是第一个和第二个输出,然后是正常的输出 这是我用来读取文件的代码: File.open(path, 'rb') { |file| file.read } 这是我用来在文件中编写的代码: File.open(p

我有一些ruby代码,可以执行并创建一些带有输出的文件

当我只运行一次代码时,我一点问题都没有,但是当我尝试在循环中运行它时,第一个文件输出正常,但是从第二个文件开始,它们都遵循一种奇怪的模式

如果我运行它三次,第一个输出是正常的,第二个是第一个输出的信息,后面是它应该具有的输出,第三个是第一个和第二个输出,然后是正常的输出

这是我用来读取文件的代码:

File.open(path, 'rb') { |file| file.read }
这是我用来在文件中编写的代码:

 File.open(path + '.txt', 'w') do |f|
  f.write text
 end
这是我用来多次运行它的代码的一部分:

while i < 4 do
    sample_path = "#{path}/samples/sample#{i}.html.erb"
    controller_grabber.grab_controllers(sample_path)
    answer_string = file_manager.read_file("#{path}/samples/sample#{i}_expected_answer.txt").gsub(/\s+/, "")
    tool_answer = file_manager.read_file("#{path}/outputs/#{file_manager.get_file_name(sample_path)}_output.txt").gsub(/\s+/, "")
    i += 1
end
结果:

[name: Show, type: @otml_file]
[name: Back, type: otml_files_path]
第二个预期结果:

[name: Show, type: @otml_file]
[name: Back, type: otml_files_path]
[name: Inicio, type: root_path]
[name: Producto, type: productos_index_path]
[name: Venta, type: venta_index_path]
[name: Proveedor, type: proveedor_index_path]
[name: Clientes, type: cliente_index_path]
第二个结果:

[name: Show, type: @otml_file]
[name: Back, type: otml_files_path]
[name: Inicio, type: root_path]
[name: Producto, type: productos_index_path]
[name: Venta, type: venta_index_path]
[name: Proveedor, type: proveedor_index_path]
[name: Clientes, type: cliente_index_path]

那看起来像香蕉。我猜您在某些代码中对该文件有一个挥之不去的引用,而这些代码被省略了——用当前的代码量很难看到

当我在一个循环中读、写、读时,我得到了你所期望的:

path = 'filename'
text = 'something'

10.times {
  p File.open(path, 'rb') { |file| file.read }

  result = File.open(path, 'w+') do |f|
    f.write text
  end

  p result

  p File.open(path, 'rb') { |file| file.read }
}
如果您确定要在每次传递时覆盖该文件,那么您可能应该在每次传递时覆盖该文件

或者给他们起不同的名字

也许有了更多的信息,我会更有帮助