# open and write to a file with ruby
open('myfile.out', 'w') do |f|
f.puts "Hello, world."
end
# an alternative approach:
open('myfile.out', 'w') do |f|
f << "Hello, world.\n"
end
# Write file
File.open("log.txt", "w") { |f| f.write "#{Time.now} - User logged in\n" }
# or
File.write("log.txt", "data...")
# Append file
File.open("foo.txt", "a") { |f| f.write "#{Time.now} - User logged in\n" }
# or
File.write("log.txt", "data...", mode: "a")
# Other Variants
File.open("out.txt", [your-option-string]) {|f| f.write("write your stuff here") }
# where your options are:
# r - Read only. The file must exist.
# w - Create an empty file for writing.
# a - Append to a file.The file is created if it does not exist.
# r+ - Open a file for update both reading and writing. The file must exist.
# w+ - Create an empty file for both reading and writing.
# a+ - Open a file for reading and appending. The file is created if it does not exist.