Ruby Reading Files
Reading a file brings its text into a program. A program can write a small file first and then read that same file back.
Read the whole file
The program writes a short file first. File.read then brings the whole text back in one string.
File.write "notes.txt", "Apples\nPears\nPlums\n"
text = File.read "notes.txt"
puts textWalk line by line
File.foreach hands one line at a time to a block. Each line still carries its ending, so chomp removes it.
File.write "fruits.txt", "Apples\nPears\nPlums\n"
File.foreach "fruits.txt" do |line|
puts line.chomp.upcase
endCheck a file exists
File.exist? checks a name before a read. It answers true for a stored file and false for a missing one.
File.write "list.txt", "Milk\nEggs\n"
found = File.exist? "list.txt"
missing = File.exist? "other.txt"
puts found
puts missingRead lines into an array
File.readlines gives one string for each line. The map call cleans each line before the array is shown.
File.write "fruits.txt", "Apples\nPears\nPlums\n"
lines = File.readlines "fruits.txt"
clean = lines.map { |line| line.chomp }
p clean
puts lines.lengthExample
File.write "scores.txt", "10\n20\n30\n"
total = 0
File.foreach "scores.txt" do |line|
total += line.to_i
end
puts "Total: #{total}"Key points
- File.write stores text in a file, ready for a later read.
- File.read brings the whole file back as one string.
- File.foreach runs a block once for each line.
- File.exist? answers true or false for a name.
- File.readlines gives an array with one string per line.
In this example, the program writes three scores into a file. File.foreach walks the file line by line. Each line becomes a number and joins the total.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does File.read give back?