Ruby:输出没有保存到文件

问题描述:

我想给一个文件作为输入,在程序中更改它,并将结果保存到输出的文件中。但输出文件与输入文件相同。 :/总的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

我过我的机器上的代码,我有正确的“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

如何:

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