File I/O & Block Closures
Ruby provides powerful tools to interact with storage drives. By combining file streams with blocks, Ruby ensures resource handles are closed automatically.
1 Auto-Closing Streams via blocks
Failing to close file handles causes resource lock errors. When you open files in Ruby using a block: `File.open(path, 'w') do |f| ... end`, Ruby automatically closes and releases the file handle when the block exits, guaranteeing safety even if exceptions occur.
2 File Operations Code
Let's run a program writing text to a file and reading it back using block-based File streams:
Ruby — File Operations
▶ Run Code
path = "demo.txt"
# Open file with block for automatic closing
File.open(path, "w") do |file|
file.puts "Ruby File operations are simple and elegant!"
file.puts "Block closures handle file closing automatically."
end # File handles are closed automatically here
# Read file contents
content = File.read(path)
puts "File Content:\n#{content}"
3 Code Challenge
Challenge: Write a program that writes three numbers to a file named `numbers.txt`. Open the file, read the numbers line-by-line, parse them as integers, and print their computed sum. Ensure you use block-based opening.