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" }