×

ruby · level 2 · unit 4 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

lines to a file, then read them one by one.

File.open opens a file in a . "w" writes from scratch, wiping the old contents. "a" will append, adding to the end. Inside the block, file.puts writes one line, and the file closes by itself at end.

To read line by line, File.foreach loops over the lines, each one keeping its newline. File.readlines("log.txt", chomp: true) gives an array of lines with the newlines already bitten off.

File.write("log.txt", "Woke up\n")
File.open("log.txt", "a") do |file|
  file.puts "Ate breakfast"
  file.puts "Went to school"
end
File.foreach("log.txt") do |line|
  puts "> #{line}"
end
p File.readlines("log.txt", chomp: true)

puts does not add a second newline when the line already ends with one.