Ruby
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Methods and Blocks
-
Section 4: Object-Oriented Ruby
-
Section 5: Metaprogramming
-
Section 6: Working with Data and Files
-
Section 7: Ruby Frameworks Overview
-
Section 8: Ecosystem and Testing
-
Section 9: Practical Projects
-
Section 10: Interview Practice
-
Section 11: Data Structures and Algorithms in Ruby
-
Section 12: More Practice Exercises
-
Section 13: Enumerable and Functional Style
-
Section 14: More OOP Practice
-
Section 15: More Testing
-
Section 16: Enumerable and Comparable Modules In Depth
-
Section 17: Ruby Standard Library: Core Utilities
-
Section 18: Ruby Standard Library: Data and Security
-
Section 19: Ruby Standard Library: CLI and Text
-
Section 20: Ruby Networking
-
Section 21: Ruby on Rails Deep Dive
-
Section 22: Ruby Metaprogramming Deep Dive
-
Section 23: Ruby Design Patterns
-
Section 24: Ruby Concurrency
-
Section 25: Ruby Testing Deep Dive
-
Section 26: Ruby Gems and Packaging
-
Section 27: Ruby Performance
-
Section 28: More Practice Exercises
-
Section 29: More Interview Practice
-
Section 30: Rails API Development
-
Section 31: Rails Authentication and Authorization
-
Section 32: Rails Testing Deep Dive
-
Section 33: Rails Performance
-
Section 34: Rails Deployment
-
Section 35: Sinatra and Lightweight Ruby Web Apps
-
Section 36: More Ruby Language Deep Dive
-
Section 37: Ruby 3.x Modern Features
-
Section 38: More Data Structures in Ruby
-
Section 39: More Practical Projects
-
Section 40: Ruby Ecosystem Tools
-
Section 41: More Practice and Review
-
Section 42: Final Practice and Mastery
-
Section 43: Ruby Interview Deep Dive
-
Section 44: Ruby Background Processing Deep Dive
-
Section 45: Ruby GraphQL
-
Section 46: Ruby Object Model Deep Dive
-
Section 47: Ruby Hanami Framework Overview
-
Section 48: Ruby gRPC and Protocol Buffers
-
Section 49: Ruby Data Processing
-
Section 50: Ruby Search Integration
-
Section 51: Ruby File Upload and Media
-
Section 52: Ruby Email and Notifications
-
Section 53: Ruby Admin Panels
-
Section 54: Ruby Feature Flags and Experimentation
-
Section 55: Ruby Monitoring and Observability
-
Section 56: Ruby Docker and Deployment Deep Dive
-
Section 57: Ruby Security Deep Dive
-
Section 58: More Advanced Metaprogramming
-
Section 59: More Final Projects
22: File I/O and Exceptions Revisited
I've seen this bug a dozen times in production code, usually written by someone who knows how to use Ruby but hasn't yet been burned by a "resource leak." Let's look at a piece of code intended to process a list of user IDs from a text file and write the "processed" versions to a new file.
def process_user_ids(input_path, output_path)
input = File.open(input_path, "r")
output = File.open(output_path, "w")
while line = input.gets
id = line.strip
# Imagine some complex validation logic here that might raise an error
raise "Invalid ID format" if id.empty?
output.puts "USER_#{id}"
end
input.close
output.close
end
At first glance, it looks fine. It opens the files, does the work, and closes them. But here is the problem: if that raise "Invalid ID format" ever triggers, the execution jumps straight out of the method. The input.close and output.close lines are never reached. In a small script, the OS will eventually clean this up. In a long-running Rails server or a background worker processing thousands of files, you'll eventually hit the "Too many open files" error, and your application will crash.
The Leak That Kills Your Server
The core issue is that we're managing the file lifecycle manually. When you call File.open without a block, you are taking full responsibility for that file handle. If an exception occurs anywhere between the open and the close, that handle stays open in memory. It's a classic leak.
Now, you could wrap everything in a begin...ensure block to make sure the files close no matter what happens. That works, but it's verbose and frankly, it's not the "Ruby way."
Letting Ruby Handle the Cleanup
The most elegant fix is to use the block form of File.open. When you pass a block to File.open, Ruby guarantees that the file will be closed as soon as the block terminates, regardless of whether it finished successfully or raised an exception. It's essentially a built-in ensure block.
def process_user_ids(input_path, output_path)
File.open(input_path, "r") do |input|
File.open(output_path, "w") do |output|
while line = input.gets
id = line.strip
raise "Invalid ID format" if id.empty?
output.puts "USER_#{id}"
end
end
end
end
Notice how much cleaner this is. We don't need to call .close explicitly. Ruby handles the plumbing, and our code focuses on the logic. If an "Invalid ID format" error occurs, Ruby closes both file handles before propagating the exception up the stack.
Guarding Against the Unexpected
Closing the file is one half of the battle; the other half is handling the fact that the file system is an unreliable place. Files get deleted, permissions change, and disks fill up. If you call File.open on a file that doesn't exist, Ruby raises an Errno::ENOENT exception.
In a real application, you don't want your whole process to die just because one config file is missing. This is where we revisit exception handling. Instead of a generic rescue (which is a bad habit because it catches NoMemoryError or Interrupt), we should be surgical about what we catch.
def safe_process_users(input_path, output_path)
process_user_ids(input_path, output_path)
rescue Errno::ENOENT => e
puts "File not found: #{e.message}. Skipping processing."
rescue Errno::EACCES => e
puts "Permission denied: #{e.message}. Please check file rights."
rescue StandardError => e
puts "An unexpected error occurred: #{e.message}"
end
By catching Errno::ENOENT and Errno::EACCES specifically, we handle the "expected" failures of the file system while still letting truly catastrophic errors (like a syntax error in our code) crash the program so we can actually find and fix them.
📋 Practical Task
The Robust Log Error Extractor
Your task is to build a utility that extracts "ERROR" level entries from a system log file and writes them to a summary file. However, this utility must be "production-ready," meaning it cannot crash due to file system issues or malformed data.
Requirements:
- Create a method
extract_errors(log_path, summary_path). - Use block-form
File.openfor both reading and writing to prevent resource leaks. - The method should only write lines that start with the word
"ERROR"to the summary file. - Implement specific
rescueblocks to handle:Errno::ENOENT: Print "Log file missing" and returnfalse.Errno::EACCES: Print "Permission denied" and returnfalse.
- If a line in the log file is not a string (e.g., if you were processing an array of mixed data) or causes a
StandardErrorduring processing, the program should log the error to the console but continue processing the rest of the file. - Return
trueif the process completed successfully.
There are no comments for now.