File Handling

Lesson 17 of 20

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.

One-Line I/O

File.write(path, text) and File.read(path) cover whole-file jobs in a single call.

Open With a Block

File.open(path) { |f| ... } closes the handle automatically when the block ends.

Line by Line

each_line yields the file one line at a time — no giant slurp for big files.

Plan for Absence

Files can be missing: check File.exist? or rescue the error it raises.