2008-09-29 101 views

回答

31
File.open("a_file", "w") do |f| 
    f.write "some data" 
end 

您还可以根据个人口味/必要性有换行符使用f << "some data"f.puts "some data"。如果要追加到文件而不是在每个打开时截断,请将"w"更改为"a"

+0

我同意传递一个块File.open。这是最安全的方法,无论发生在那里(正确的执行,异常等),文件保证被正确关闭。 – webmat 2008-09-30 00:35:23

-2
filey = File.new("/path/to/the/file", APPEND) 
filey.puts "stuff to write" 
2

超越File.newFile.open(和所有其他有趣的东西IO),你可能希望,特别是如果你从保存和加载回Ruby和您的数据中的对象,来看看使用Marshal保存和加载直接对象。

0

使用文件::开是最好的一段路要走:

File.open("/path/to/file", "w") do |file| 
    file.puts "Hello file!" 
end 

如前所述,您可以使用的“一”,而不是“W”追加到该文件。可能有其他模式可用,列于ri IORuby Quickref

相关问题