I would like to write some data to a file in Ruby. What is the best way to do that?
A:
filey = File.new("/path/to/the/file", APPEND)
filey.puts "stuff to write"
thesmallprint
2008-09-29 21:21:56
+6
A:
File.open("a_file", "w") do |f|
f.write "some data"
end
You can also use f << "some data"
or f.puts "some data"
according to personal taste/necessity to have newlines. Change the "w"
to "a"
if you want to append to the file instead of truncating with each open.
Pi
2008-09-29 21:23:15
I concur with passing a block to File.open. This is the safest method as whatever happens in there (correct execution, exception, etc), the file is guaranteed to be closed correctly.
webmat
2008-09-30 00:35:23
+2
A:
Beyond File.new or File.open (and all the other fun IO stuff) you may wish, particularly if you're saving from and loading back into Ruby and your data is in objects, to look at using Marshal to save and load your objects directly.
Mike Woodhouse
2008-09-29 21:33:00
A:
Using File::open is the best way to go:
File.open("/path/to/file", "w") do |file|
file.puts "Hello file!"
end
As previously stated, you can use "a" instead of "w" to append to the file. May other modes are available, listed under ri IO
, or at the Ruby Quickref.
jtbandes
2008-09-30 03:05:38