How to append text to a file with Ruby

Ruby file FAQ: How do I append text to a file in Ruby?

Solution: Appending text to a file with Ruby is similar to other languages: you open the file in "append" mode, write your data, and then close the file.

Here's a quick example that demonstrates how to append "Hello, world" to a file named myfile.out in the current directory:

open('myfile.out', 'a') { |f|
  f.puts "Hello, world."
}

It's very important to note that I use f.puts in that example. If you're used to using the puts method, f.puts is just like it, except your writing to your file, f.

Variations

There are actually quite a few different ways to append data to a file. Here's the same example, using the do/end block syntax:

open('myfile.out', 'a') do |f|
  f.puts "Hello, world. It's me again."
end

And in this example I show how to append to the file using the << operator:

open('myfile.out', 'a') do |f|
  f << "and again ...\n"
end

(Note the use of the \n at the end of the string when using the << operator. That's something that puts does for you automatically.)

Writing multiple lines

Finally, if you want to append more than one line at a time, here's a quick demo showing how to do this:

open('myfile.out', 'a') { |f|
  f << "Four score\n"
  f << "and seven\n"
  f << "years ago\n"
}

Share it!

There’s just one person behind this website; if this article was helpful (or interesting), I’d appreciate it if you’d share it. Thanks, Al.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.