← Back to Ruby Course | Chapter 11: File I/O & Exceptions | Lesson 2 of 6

File.open with a Block

In this page:

  1. File.open with a Block

File.open with a Block

File.open("path", "mode") { |file| ... } opens a file and automatically closes it once the block finishes, even if an error occurs inside -- avoiding the need for manual cleanup. Mode strings like "r" (read), "w" (write), and "a" (append) control how the file is opened. This block form is the idiomatic, safe way to work with files in Ruby.

Note: Always prefer the block form of File.open -- it guarantees the file is closed automatically, even if an exception is raised.

Example: File.open with a Block

markup
File.open("notes.txt", "w") do |file|
  file.puts "Line one"
  file.puts "Line two"
end

File.open("notes.txt", "r") do |file|
  file.each_line { |line| puts line.chomp }
end
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.