ruby · level 2 · unit 4 · lesson 2
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Write or append? What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
File.open("list.txt", "w") { |file| file.puts "eggs" }
File.open("list.txt", "a") { |file| file.puts "jam" }
File.open("list.txt", "a") { |file| file.puts "tea" }
p File.readlines("list.txt", chomp: true)
your turn
Your turn. Log your workout.
Fill in three exercises. Each one is appended to the log, then the log is read back.
fix it
The guest book forgets every guest but one. Fix it!
- Only the last guest is left. What does mode
"w"do to the file each time it opens? "w"writes from scratch, wiping the file on every turn. You want to add to the end instead.- Change "w" to "a" on line 2, then press run.
nailed it
your files can grow line by line. :D
- Mode
"w"starts fresh. Mode"a"appends to the end. file.putswrites one line inside aFile.openblock.File.readlines(name, chomp: true)gives tidy lines.
new words in your collection
- append
- mode
This lesson isn’t saved. A free account remembers every lesson you finish.