2015-10-05 80 views
0

我試圖截斷並寫入新的生產線,以一個文件的內容並打印後的空白:紅寶石印刷書寫線

target = File.open(ARGV.first, 'w') 

puts "we are going to clear the file first" 

target.truncate(0) 

puts "give me 1 line" 
line1 = $stdin.gets.chomp 
puts "give me another line!" 
line2 = $stdin.gets.chomp 

puts "we are gonna write the text into the file now" 
target.write(line1) 
target.write("\n") 
target.write(line2) 
target.write("\n") 

newfile = open(ARGV.first, 'r') 
puts newfile.read 

puts "we will close the file now" 
target.close 

然而,紅寶石保持印刷空白。我寫的文本文件有我輸入的文本。我不確定發生了什麼事。

+0

即使它是空的,請將您的程序**的輸出發佈到問題主體中,而不是註釋**。如果不知道實際產出與預期產出的關係,我們就會感到無助 – onebree

+1

其次,我改變了你的標籤。 RoR是一個沒有專注於LRTHW的Web框架。下一次,請選擇_correct_標籤,它們不一定是SO上最受歡迎的標籤。 – onebree

回答

1

您需要先關閉文件,然後再嘗試讀取文件。

target = File.open(ARGV.first, 'w') 

puts "we are going to clear the file first" 

target.truncate(0) 

puts "give me 1 line" 
line1 = $stdin.gets.chomp 
puts "give me another line!" 
line2 = $stdin.gets.chomp 

puts "we are gonna write the text into the file now" 
target.write(line1) 
target.write("\n") 
target.write(line2) 
target.write("\n") 

puts "we will close the file now" 
target.close 

newfile = open(ARGV.first, 'r') 
puts newfile.read 
+0

非常感謝Joard!我很想知道背後的理論 - 爲什麼我必須先關閉文件,並在代碼背後實際發生了什麼? –