Why Your Ruby Scripts Keep Breaking Files (and How to Fix Them)

File Handling in Ruby — Reading, Writing, and What Could Go Wrong

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


๐Ÿ”œ 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

Popular posts from this blog

Why Every Developer Should Meet Ruby: A Friendly Introduction

This is Ruby. And Ruby knows how to block — like a bouncer for bad code. ๐Ÿ”ฅ

Iterators in Ruby — Think Less Looping, More Logic