Ruby Language File and I/O Operations Writing a string to a file


Example

A string can be written to a file with an instance of the File class.

file = File.new('tmp.txt', 'w')
file.write("NaNaNaNa\n")
file.write('Batman!\n')
file.close

The File class also offers a shorthand for the new and close operations with the open method.

File.open('tmp.txt', 'w') do |f|
  f.write("NaNaNaNa\n")
  f.write('Batman!\n')
end

For simple write operations, a string can be also written directly to a file with File.write. Note that this will overwrite the file by default.

File.write('tmp.txt', "NaNaNaNa\n" * 4 + 'Batman!\n')

To specify a different mode on File.write, pass it as the value of a key called mode in a hash as another parameter.

File.write('tmp.txt', "NaNaNaNa\n" * 4 + 'Batman!\n', { mode: 'a'})