0
0
Rubyprogramming~5 mins

File.open with block (auto-close) in Ruby

Choose your learning style9 modes available
Introduction

Using File.open with a block helps you open a file, do something with it, and then automatically close it when done. This keeps your program safe and clean.

When you want to read or write a file and be sure it closes right after.
When you want to avoid forgetting to close a file, which can cause errors.
When you want your code to be simple and easy to understand.
When working with temporary files that only need to be open briefly.
When you want to safely handle files without extra cleanup code.
Syntax
Ruby
File.open('filename', 'mode') do |file|
  # work with file here
end

The mode can be 'r' for reading, 'w' for writing, and others.

The file is automatically closed after the block finishes, even if errors happen.

Examples
Open a file to read its content and print it, then close automatically.
Ruby
File.open('example.txt', 'r') do |file|
  puts file.read
end
Open a file to write text, then close it automatically.
Ruby
File.open('output.txt', 'w') do |file|
  file.puts 'Hello, world!'
end
Open a file to add text at the end (append mode), then close it.
Ruby
File.open('data.txt', 'a') do |file|
  file.puts 'Add this line'
end
Sample Program

This program writes 'Hi there!' to a file, then reads it back and prints it. The file closes automatically after each block.

Ruby
File.open('greeting.txt', 'w') do |file|
  file.puts 'Hi there!'
end

File.open('greeting.txt', 'r') do |file|
  content = file.read
  puts "File says: #{content.strip}"
end
OutputSuccess
Important Notes

Always use the block form of File.open to avoid leaving files open.

If an error happens inside the block, Ruby still closes the file safely.

You can use different modes like 'r', 'w', 'a', 'r+', depending on your need.

Summary

File.open with block opens a file and closes it automatically after the block.

This helps keep your program safe and simple.

Use it whenever you work with files to avoid mistakes.