Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to write to a file in Ruby? [closed]

Tags:

file-io

ruby

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

like image 230
Sixty4Bit Avatar asked Sep 29 '08 21:09

Sixty4Bit


People also ask

Which method is used writing to the file in Ruby?

With the help of syswrite method, you can write content into a file.

What is __ file __ in Ruby?

__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.

What are the Ruby file open modes?

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.


1 Answers

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.

like image 130
Alex M Avatar answered Oct 07 '22 14:10

Alex M