Why Your Ruby Scripts Keep Breaking Files (and How to Fix Them)
File Handling in Ruby — Reading, Writing, and What Could Go Wrong
CodeCraft Diaries #9 • For Freshers, Students & Curious Developers
“If you’ve never accidentally deleted a file while testing your script, are you even a developer?”
Working with files is one of the first real-world things you’ll do in any programming language. Whether it's reading a config, logging errors, or saving user data — file I/O is everywhere.
And Ruby? Ruby makes it refreshingly simple. Until you forget to close the file... ๐
๐ Reading from a File
Let’s say we have a file called data.txt
.
File.open("data.txt", "r") do |file|
puts file.read
end
What’s happening here?
"r"
means “read mode”file.read
grabs the entire content- The block auto-closes the file (thank you, Ruby!)
✍️ Writing to a File
File.open("log.txt", "w") do |file|
file.puts "This is a new log entry."
end
Note: "w"
mode overwrites the file.
If the file doesn’t exist? Ruby creates it. Ruby’s polite like that.
➕ Appending to a File
File.open("log.txt", "a") do |file|
file.puts "Another entry added!"
end
"a"
is append mode — it writes at the end without touching existing content.
๐ฃ What Could Go Wrong?
- Forgetting to close the file (can cause memory leaks or locked files)
- Using the wrong mode — accidentally overwriting data with
"w"
- Trying to read a file that doesn’t exist (handle it with grace!)
Use File.exist?
to check first:
if File.exist?("data.txt")
puts "File found!"
else
puts "Oops, no file here."
end
๐ Bonus: Read Line by Line
File.foreach("data.txt") do |line|
puts line
end
Efficient for large files — reads one line at a time.
๐งช Mini Challenge
Write a Ruby script that takes a file name and a message from the user, and appends the message to that file. Bonus: Add a timestamp to each entry!
๐ Quick Recap
"r"
= Read"w"
= Write (overwrite!)"a"
= Append- Always use
File.open
with a block to auto-close - Check file existence before reading
๐ Related Reads
- Modules & Mixins in Ruby — Sharing Code Without the Mess
- Procs and Lambdas in Ruby — The Cousins You Need to Know
๐ Up Next in CodeCraft Diaries
“Error Handling in Ruby — Don’t Panic, Rescue!”
Because real code doesn’t always go as planned — and that’s okay.
Comments
Post a Comment