What is the best way to write to a file in Ruby? [closed]
Question
I would like to write some data to a file in Ruby. What is the best way to do that?
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'
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