File.open with a Block
In this page:
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
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: