Ruby File I/O — read, write, File.each_line — Complete Beginner Guide
Learning Objectives
- Open and close files safely
- Read entire files and individual lines
- Write and append text to files
- Process large files with File.each_line
- Prefer block form to avoid resource leaks
Why Files Matter
Programs often need to persist data beyond a single run. Configuration files, logs, exports, and reports all rely on file input and output. Ruby provides a straightforward File class plus convenient one-liners for common tasks.
Opening and Closing Files
The most explicit approach opens a file, works with it, then closes it.
file = File.open("notes.txt", "w")
file.puts "First line"
file.close
Modes control intent: w overwrites, a appends, and r reads. Always close files when you finish so operating system resources are released promptly.
The Safer Block Form
Ruby automatically closes the file when you pass a block to File.open.
File.open("notes.txt", "w") do |file|
file.puts "Written safely"
file.puts "Closed automatically"
end
Even if an exception occurs inside the block, cleanup still runs. Prefer this pattern in production code because it prevents accidental leaks.
Reading Files
Reading everything
content = File.read("notes.txt")
puts content
read loads the entire file into one string, which is convenient for small files but memory-heavy for huge ones.
Reading line by line
File.foreach("notes.txt") do |line|
puts line
end
foreach yields one line at a time, keeping memory usage low regardless of file size.
Using File.each_line
File.each_line("notes.txt") do |line|
puts line.strip
end
each_line provides the same streaming behavior. strip removes trailing newline characters so your output stays tidy.
Checking File Facts
path = "notes.txt"
puts File.exist?(path)
puts File.size(path)
puts File.basename(path)
exist? prevents errors from reading missing files, size reports bytes, and basename extracts the filename without directories.
Writing Files
File.write("report.txt", "Monthly summary")
write creates or overwrites the file with the provided content in one call. For multiple lines, open the file in write mode with a block and call puts repeatedly.
Appending Data
File.open("log.txt", "a") do |file|
file.puts "Event at #{Time.now}"
end
Append mode adds to the end without destroying existing content, which is exactly what logs need.
A Practical Example
names = ["Ada", "Grace", "Linus"]
File.open("names.txt", "w") do |file|
names.each do |name|
file.puts name
end
end
File.each_line("names.txt") do |line|
puts "Read: #{line.strip}"
end
This script writes three names, then reads them back. Patterns like this appear constantly in data export and import tasks.
Working With Paths
puts File.dirname("/home/user/data.txt")
puts File.extname("report.csv")
puts File.join("home", "user", "data.txt")
dirname, extname, and join help you manipulate paths portably across operating systems instead of concatenating strings by hand.
Common Mistakes
- Using write mode when you meant append, erasing existing data
- Forgetting to close files by skipping the block form
- Loading massive files entirely into memory with read
- Ignoring encoding issues when processing non-ASCII text
- Assuming a file exists without checking exist? first
Each of these issues causes data loss or crashes, so build careful habits early.
Working with Large Files
Reading an entire file into memory can be wasteful when the file is very large. Instead of using read or readlines on a huge log, iterate line by line with each line or use the scanner class for pattern based processing. This streaming approach keeps memory usage constant regardless of file size and is essential for production scripts that process unbounded data.
Path Handling Best Practices
Always build file paths using the file join method or the path name class rather than concatenating strings with slashes. This approach produces correct separators on every operating system and avoids subtle bugs when your code moves between development machines and servers running different platforms.
Use expand path to convert relative paths into absolute ones based on the current working directory. This is especially helpful in scripts that must locate configuration files or data directories regardless of where the script is invoked from. Combining expand path with file dirname gives you reliable access to sibling files and folders.
Binary vs Text Mode
By default Ruby opens files in text mode on some platforms which can translate line endings unexpectedly. Pass rb or wb flags when you need exact byte level control, such as when processing images or other binary formats. Knowing when to use each mode prevents silent data corruption that only shows up after deployment on a different operating system.
Key Takeaways
💡
- File.open with a block guarantees automatic closing
- read loads everything; foreach and each_line stream line by line
- Mode w overwrites while mode a appends
- File.write offers a quick one-call write for simple cases
- Always verify a file exists before reading or writing
Practice Questions
- Write a block-form snippet that writes three lines to a file.
- What is the difference between modes w and a?
- Process a log file with File.each_line and print line numbers.
- Why is the block form of File.open safer than manual close?
- Which method checks whether a file exists before you open it?
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- Forgetting constraints — Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions