I would like to write some data to a file in Ruby. What is the best way to do that?
With the help of syswrite method, you can write content into a file.
__FILE__ is the name of the current file. The script bellow test if the current file is the one we use on the command line, with : ruby script.rb if __FILE__ == $0 puts "we are running this file (it's not included somewhere)" end.
Ruby allows the following open modes: "r" Read-only, starts at beginning of file (default mode). "r+" Read-write, starts at beginning of file. "w" Write-only, truncates existing file to zero length or creates a new file for writing.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With