0
0
RubyHow-ToBeginner · 3 min read

How to Append to File in Ruby: Simple Syntax and Example

In Ruby, you can append to a file by opening it with 'a' mode using File.open and then writing to it. For example, File.open('file.txt', 'a') { |f| f.puts 'text' } adds text at the end without overwriting existing content.
📐

Syntax

To append to a file in Ruby, use File.open with the mode 'a'. This mode opens the file for writing and moves the cursor to the end of the file. You can then write text using methods like puts or write. The file is automatically closed after the block finishes.

ruby
File.open('filename.txt', 'a') do |file|
  file.puts 'Your text here'
end
💻

Example

This example appends two lines of text to a file named example.txt. If the file does not exist, Ruby creates it. Each puts adds a new line at the end.

ruby
File.open('example.txt', 'a') do |file|
  file.puts 'Hello, world!'
  file.puts 'Appending this line.'
end

puts File.read('example.txt')
Output
Hello, world! Appending this line.
⚠️

Common Pitfalls

One common mistake is using 'w' mode instead of 'a'. The 'w' mode overwrites the entire file, erasing existing content. Another pitfall is forgetting to close the file, but using a block with File.open handles this automatically.

ruby
wrong = File.open('file.txt', 'w') { |f| f.puts 'Overwrite!' }
right = File.open('file.txt', 'a') { |f| f.puts 'Append!' }
📊

Quick Reference

ModeDescription
'a'Open file for appending, create if not exists
'w'Open file for writing, overwrite existing content
'r'Open file for reading only

Key Takeaways

Use 'a' mode with File.open to append without erasing existing file content.
Always use a block with File.open to ensure the file closes automatically.
Avoid 'w' mode when you want to add to a file, as it overwrites the file.
If the file does not exist, 'a' mode creates it automatically.
Use puts to add lines with a newline, or write for raw text.