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

File.open with a Block

File.open with a block opens a file, lets you work with it, and closes it automatically when you finish. It is like a door that shuts itself behind you.

In this page:

  1. File.open with a Block
Syntax
ruby
File.open("path", "mode") do |file|
  file.puts "text"
end

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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using "w" mode on a file that should keep its content, which erases it; use "a" to append.
  2. Using File.open without a block and forgetting file.close, leaving it open.
  3. Reading with "w" mode or writing with "r" mode, which raises IOError.
🔒

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.