Writing a string to a file
suggest changeA 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 also be 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 append, pass mode as a keyword. A positional hash is taken as a byte offset and raises TypeError.
File.write('tmp.txt', "NaNaNaNa\n" * 4 + "Batman!\n", mode: 'a')
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents