tags:

views:

555

answers:

5

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
+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
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
+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
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
A: 
require 'rio'
rio('foo.txt') < 'bar'

http://rio.rubyforge.org/

alex2k8