Files

View saved

Write a file

Blocks close files automatically.

File.write("notes.txt", "Hello from Ruby\n")

Read a file

Read the whole file or stream lines.

puts File.read("notes.txt")

File.foreach("notes.txt") do |line|
  puts line
end

Append

Open with append mode when you need to add lines.

File.open("notes.txt", "a") { |f| f.puts "Another line" }

File tips

  • Handle missing files with rescue or File.exist?
  • Prefer block forms so files close reliably
  • Avoid letting users pass unchecked paths
  • Pathname in the standard library offers a friendlier API

Comments

One comment per signed-in account. Comments are saved with this page’s URL.