Reading and writing files
Until now your program forgets everything as soon as the cell is done. To remember something – notes, high scores, measurements – you write it to a file. In Ruby that is two lines: File.write creates the file (or overwrites it) and File.read brings the whole content back as a string:
File.write("notes.txt", "buy bacon\nbuy eggs\n")
File.read("notes.txt")The file appears as a download below the cell – and show_files shows you the folder you are working in. Whether a file exists you ask with File.exist? before reading it:
p File.exist?("notes.txt")
p File.exist?("secret.txt")
show_filesMost of the time you want a file line by line: lines splits the string at the line breaks, chomp: true cuts the breaks off right away. Then you have an array and can do everything you know from lesson 8 (arrays) with it:
lines = File.read("notes.txt").lines(chomp: true)
lines.each_with_index { |line, i| puts "#{i + 1}. #{line}" }
lines.lengthCareful: File.write replaces the content. To append something, read the file first, add the new text and write it all back:
File.write("notes.txt", File.read("notes.txt") + "buy bread\n")
puts File.read("notes.txt")One line per entry, the fields separated by commas – that is what the simplest table file looks like (CSV). Reading it means: go through it line by line, cut each with split and use the parts:
File.write("prices.csv", "bacon,4.50\negg,1.20\ncoffee,3.00\n")
total = 0
File.read("prices.csv").lines(chomp: true).each do |line|
item, price = line.split(",")
total += price.to_f
end
totalAnd for tidying up: File.delete removes a file. After that it is gone – File.exist? says false, and File.read would report an error.
File.delete("prices.csv")
File.exist?("prices.csv")There, the same methods write real files to disk – File.write("notes.txt", …) lands in the folder you started ruby in. For appending there is also File.open("notes.txt", "a") { |f| f.puts "buy bread" }, and Dir.glob("*.txt") lists every text file in the folder. Here in the browser the files live on this page only: what a cell writes appears as a download below it – that is how you take it with you.
In the advanced course, lesson 116 (saving data), you store whole records as CSV, JSON and YAML with the same moves.
shopping.txt with three lines – one item in each. Then read it back and store the three lines, without their line breaks, in the array items.# Write shopping.txt with three lines (one item each),
# then read it back: the lines, without their line breaks, in items
points.txt, a name and a number per line, separated by a comma. Read the file back and work out total, all the points added up (22), and best, the name with the most points ("Kaz"). split cuts a line, max_by from lesson 13 finds the champion.File.write("points.txt", "Kaz,12\nIsi,7\nChunky,3\n")
# total = ... # all the points added up: 22
# best = ... # the name with the most points: "Kaz"