2011-03-20 111 views
0

我想給一個文件作爲輸入,在程序中更改它,並將結果保存到輸出的文件中。但輸出文件與輸入文件相同。 :/總的n00b問題,但我在做什麼錯?:Ruby:輸出沒有保存到文件

puts "Reading Celsius temperature value from data file..." 
num = File.read("temperature.dat") 
celsius = num.to_i 
farenheit = (celsius * 9/5) + 32 
puts "Saving result to output file 'faren_temp.out'" 
fh = File.new("faren_temp.out", "w") 
fh.puts farenheit 
fh.close 
+0

你應該傳遞一個塊'File'的優勢,因此它autocloses您的文件給你。查看[Ruby的IO文檔](http://rubydoc.info/stdlib/core/1.9.2/IO),並搜索它們如何使用塊。文件從IO繼承,所以你會自動獲得很多很酷的Ruby良善。 – 2011-03-20 19:07:54

+1

溫度值是否在-40℃? :-) – matt 2011-03-20 21:37:52

+0

你在輸入文件中有什麼,你在輸出文件中有什麼? – 2011-03-20 22:12:51

回答

1

我過我的機器上的代碼,我有正確的「faren_temp.out」文件。沒有什麼是錯的 ?

Temperature.dat

23 

faren_temp.out

73 

你只需要在結果的問題。 「攝氏度」必須是一個浮點型變量才能進行浮點除法(而不是整數除法)。

puts "Reading Celsius temperature value from data file..." 
num = File.read("temperature.dat") 
celsius = num.to_f # modification here 
farenheit = (celsius * 9/5) + 32 
puts "Saving result to output file 'faren_temp.out'" 
fh = File.new("faren_temp.out", "w") 
fh.puts farenheit 
fh.close 

faren_temp.out

73.4 
+0

爲什麼我必須使用花車? – Sophie 2011-03-21 01:00:10

+0

因爲整數除以另一個整數會返回一個整數。 5/3 = 1; 5.0/3.0 = 1.666 ... – 2011-03-21 08:58:03

+0

重點不是準確的,它是讓它工作。 :P謝謝,浮動更適合這個應用程序 – Sophie 2011-03-21 18:24:11

0

如何:

puts "Reading Celsius temperature value from data file..." 
farenheit = 0.0 
File.open("temperature.dat","r"){|f| farenheit = (f.read.to_f * 9/5) + 32} 
puts "Saving result to output file 'faren_temp.out'" 
File.open("faren_temp.out","w"){|f|f.write "#{farenheit}\n"}