That’s a solid approach! But if you want to append data instead of overwriting the file, you can use ‘a’ mode instead of ‘w’:
File.open("output.txt", "a") do |file|
file.puts("This line gets appended instead of replacing previous content.")
end
Additionally, it’s good practice to handle potential file errors using begin-rescue blocks:
begin
File.open("output.txt", "w") { |file| file.puts("Writing safely!") }
rescue IOError => e
puts "File write failed: #{e.message}"
end
This ensures that your program doesn’t crash if something goes wrong, like insufficient permissions or disk space issues."