Question

I would like to write some data to a file in Ruby. What is the best way to do that?

Was it helpful?

Solution

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.

OTHER TIPS

require 'rio'
rio('foo.txt') < 'bar'

http://rio.rubyforge.org/

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.

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.

filey = File.new("/path/to/the/file", APPEND)
filey.puts "stuff to write"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top