File I/O
Ruby is a dynamic, beginner-friendly programming language, and file input/output lets your programs persist data — reading from and writing to files on disk so work survives between runs.
Learn File I/O in our free Ruby course — a beginner-friendly interactive lesson with worked examples, a practice exercise and a quick reference.
Part of the free Ruby course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
By the end of this lesson you'll write, read, and append files safely with the block form, and process them line by line.
What You'll Learn in This Lesson
1️⃣ Writing, Reading, and Appending
Open a file with File.open(name, mode) and a block — the file closes automatically when the block ends. Use "w" to write (overwrites), "a" to append, and read with File.read or File.readlines .
2️⃣ Processing Files Line by Line
For larger files, process one line at a time with each_line or File.foreach so you don't load everything into memory. Call chomp to drop the trailing newline, and check files first with File.exist? .
Your turn. Write a to-do list to a file, then read it back numbered. Confirm the TODO details, then run it locally.
Mini-Challenge: A Line-Count Report
Write a file, then count its total and non-blank lines with File.foreach . Run with ruby report.rb locally.
Common Errors (and the fix)
- "Errno::ENOENT: No such file" — Reading a file that doesn't exist. Check File.exist? first, or create it.
- "w" erased my data — "w" overwrites. Use "a" to add without erasing.
- Double blank lines — Lines keep their \n ; call chomp before puts .
- Forgetting to close (non-block form) — Without a block you must close ; just use the block form.
- Wrong working directory — Relative paths are relative to where you run Ruby. cd into the right folder.
Pro Tips
- 💡 File.write shortcut: File.write("x.txt", "hi") writes a whole string in one call.
- 💡 foreach for big files: it streams lines, so memory stays flat regardless of file size.
- 💡 Structured data: use the built-in CSV and JSON libraries for tables and objects.
📋 Quick Reference — File I/O
Concept
Ruby Syntax
Write (block)
File.open(f,"w") { |x| }
Quick write
File.write(f, str)
Read whole
File.read(f)
Read lines
File.readlines(f)
Stream lines
File.foreach(f) { }
Exists?
File.exist?(f)
Frequently Asked Questions
🎉 Lesson Complete!
- ✅ Open files with File.open(name, mode) and a block
- ✅ The block form auto-closes the file safely
- ✅ Modes: "r" read, "w" overwrite, "a" append
- ✅ read , readlines , and foreach read in different ways
- ✅ chomp removes trailing newlines
- ✅ Next lesson: Metaprogramming Intro — code that writes code
Practice quiz
Why prefer the block form of File.open?
- It is faster
- It reads files in parallel
- It automatically closes the file, even if an exception is raised
- It compresses the file
Answer: It automatically closes the file, even if an exception is raised. The block form passes you the file and closes it automatically when the block ends, even on errors.
What does the "w" file mode do?
- Opens for writing and truncates (overwrites) existing content
- Reads the file
- Appends to the end
- Opens in binary mode
Answer: Opens for writing and truncates (overwrites) existing content. "w" opens for writing and empties the file first, so it overwrites; it also creates the file if missing.
Which mode appends new content without erasing what's there?
- "r"
- "w"
- "x"
- "a"
Answer: "a". "a" opens for appending, adding to the end without truncating.
What does File.read return?
- An array of lines
- The entire file as one string
- One line at a time
- The file size
Answer: The entire file as one string. File.read loads and returns the whole file as a single string.
What does File.readlines return?
- An array with one string per line
- One big string
- The number of lines
- A lazy enumerator
Answer: An array with one string per line. File.readlines returns an array, one string per line — handy for indexing or counting.
Which is the memory-efficient way to process a large file line by line?
- File.read
- File.readlines
- File.foreach / each_line
- File.size
Answer: File.foreach / each_line. File.foreach and each_line stream one line at a time, keeping memory flat regardless of file size.
What does do to a line read from a file?
- Uppercases it
- Removes a trailing newline
- Splits it into words
- Adds a newline
Answer: Removes a trailing newline. Each read line keeps its trailing ; chomp removes it so puts doesn't double-space.
Which check confirms a file exists before reading it?
- File.size
- File.read
- File.open
- File.exist?
Answer: File.exist?. File.exist?(name) returns true/false; checking it avoids Errno::ENOENT.
Which shortcut writes a whole string to a file in one call?
- File.put
- File.write(name, str)
- File.save
- File.append
Answer: File.write(name, str). File.write("x.txt", "hi") writes the string in a single call.
What error do you get reading a file that doesn't exist?
- ZeroDivisionError
- ArgumentError
- Errno::ENOENT (No such file)
- TypeError
Answer: Errno::ENOENT (No such file). Reading a missing file raises Errno::ENOENT; check File.exist? first or create it.
Continue this course
- Previous: Regular Expressions
- Next: Metaprogramming Intro