Read, write and walk through files the Ruby way — open with a block and the handle closes itself, errors or not.
The big picture
Files are just text
Ruby treats files as ordinary strings and iterators: write one, slurp one, or walk it line by line — and let blocks handle the cleanup.
1
One-Line I/O
File.write(path, text) and File.read(path) cover whole-file jobs in a single call.
2
Open With a Block
File.open(path) { |f| ... } closes the handle automatically when the block ends.
3
Line by Line
each_line yields the file one line at a time — no giant slurp for big files.
4
Plan for Absence
Files can be missing: check File.exist? or rescue the error it raises.
Files are just text
One-Line I/O1File.write(path, text) and File.read(path) cover whole-file jobs in a single call.
Open With a Block2File.open(path) { |f| ... } closes the handle automatically when the block ends.
Line by Line3each_line yields the file one line at a time — no giant slurp for big files.
Plan for Absence4Files can be missing: check File.exist? or rescue the error it raises.
4 building blocks make up Files are just text
How it works
The life of a file handle
Press Run and follow one handle from birth to automatic close.
Watch it run
Write it, read it, walk it
One file, three techniques: a one-line write, a full read, and each_line measuring every line.
files.rb
1File.write("notes.txt","milk\nbread\neggs")
2text = File.read("notes.txt")
3puts text
4puts"---"
5
6File.open("notes.txt")do|file|
7 file.each_line do|line|
8puts line.length
9end
10end
main
File.write creates notes.txt in one call and returns 15 — the number of bytes it stored.
Memory
no variables yet — press play
Console
output appears as the program runs…
Step 1/12
Practice
Match the file toolkit
Click a tool, then click its job to lock the pair.
5 conceptsTap a card to expand
?File.read(path)drops into place
?File.write(path, s)drops into place
?File.open(path) { |f| }drops into place
?each_linedrops into place
?File.exist?(path)drops into place
Challenge
Predict the output
Counting, splitting and shouting — all one-liners.
list.rb
1File.write("list.txt","a\nb\nc")
2n = File.read("list.txt").length
3puts n
4lines = File.read("list.txt").lines
5puts lines.length
6puts File.read("list.txt").upcase
Your predicted output — one line per console line
Hint: length counts characters including newlines (5). lines splits into an array of 3 strings. upcase returns an ALL-CAPS copy, and puts prints each embedded newline as a new line.
Recap
Key takeaways
Key takeaways5 takeaways
01
File.write and File.read are one-liners for whole-file jobs.
02
File.open with a block closes the handle automatically, even on errors.
03
each_line processes a file line by line without slurping it all.
04
Always plan for missing files — File.exist? or rescue the error.
05
The lines method turns file text into an array of line strings.