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:
Syntax
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
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
Login to try C/C++/Java/PHP code in the editor
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
- Using
"w"mode on a file that should keep its content, which erases it; use"a"to append. - Using
File.openwithout a block and forgettingfile.close, leaving it open. - Reading with
"w"mode or writing with"r"mode, which raisesIOError.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: