ruby · level 2 · unit 4 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A keeps your data after the program stops.
Variables vanish when a program ends. A file is a named lump of saved data that stays. File.write("notes.txt", text) saves a string into a file, and File.read("notes.txt") hands the whole file back as one string.
The name you give is a . A plain name like "notes.txt" means the folder the program is running in, so keep to paths like that. File.exist? asks whether a file is there yet.
On Gwecode, every run starts in a fresh, empty folder, so write a file and read it back in the same program.
p File.exist?("notes.txt")
File.write("notes.txt", "Buy milk\nFeed the cat\n")
p File.exist?("notes.txt")
puts File.read("notes.txt") File.write wipes out whatever the file held before, so the file always starts fresh.
guess first
Write twice, read once. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
File.write("pet.txt", "Rex")
File.write("pet.txt", "Biscuit")
puts File.read("pet.txt")
your turn
Your turn. Keep a diary.
Write today's diary entry in the blank, then press run to save it and read it back.
fix it
The program crashes reading the score. Can you fix it?
- Read the error. It says there is no such file. Which file is it looking for?
- Line 1 saves score.txt, but line 2 reads scores.txt. The names must match exactly.
- Change scores.txt to score.txt on line 2, then press run.
nailed it
you saved your first file. :D
File.writesaves a string into a file, replacing it.File.readhands the whole file back as one string.- Use plain names like
"notes.txt"for your paths.
new words in your collection
- file
- path
This lesson isn’t saved. A free account remembers every lesson you finish.