2016-10-19 15 views
-1

我有一些應該執行的ruby代碼並創建一些帶有輸出的文件。在循環中寫入多個文件的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 

關於grab_controllers我呼籲寫一次文件。我真的不知道是什麼原因可能是,試圖建立controller_grabber和file_manager的新實例,但它並沒有奏效

這裏是我得到

首先期望的結果輸出的一些例子:

[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] 

回答

0

這似乎是香蕉。我猜你在一些被省略的代碼中對文件的引用持久 - 很難用當前的代碼量來看。

當我讀,寫,在一個循環中讀取,我得到你所期望的:

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 } 
} 

如果你一定要覆蓋在每次通過的文件,那麼你或許應該delete文件每次通過。

,或給他們不同的名字......

更多信息也許我可以提供更多的幫助。

相關問題