Ruby Writing Files
Writing a file stores text outside the program. The text stays on disk after the program ends, ready for a later read.
Write and count bytes
File.write stores the string and gives back a count. The count is the number of bytes written.
count = File.write "note.txt", "Hello files"
puts countWrite with a block
File.open with mode "w" opens a file for writing. The block writes two lines, and the file closes when the block ends.
File.open "note.txt", "w" do |file|
file.puts "First line"
file.puts "Second line"
end
text = File.read "note.txt"
puts textAppend to a file
Mode "a" keeps the old content in place. The new line joins the end of the file.
File.write "log.txt", "Start\n"
File.open "log.txt", "a" do |file|
file.puts "More"
end
text = File.read "log.txt"
puts textExample
File.write "report.txt", "Report\n"
File.open "report.txt", "a" do |file|
file.puts "Sales rose"
file.puts "Costs fell"
end
text = File.read "report.txt"
puts textKey points
- File.write stores a string in a file and replaces old content.
- File.write gives back the number of bytes it wrote.
- File.open with a block hands over a file object to write to.
- The block form closes the file by itself at the end.
- Mode "a" appends to the end of a file instead of replacing it.
In this example, File.write stores the first line of a report. File.open then appends two more lines with mode "a". The read at the end proves all three lines stayed in the file.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does File.write give back after storing text?