×

ruby · level 2 · unit 4 · lesson 1

  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

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.