Ruby file FAQ: How do I write to a file in Ruby?
Writing to a file with Ruby
Many times when you're working with Ruby scripts you need to be able to write text information to a file. Writing text to a file with Ruby is reasonably straightforward. Just like many other languages, you need to open the file in "write" mode, write your data, and then close the file.
Here's a quick Ruby "write to file" example that demonstrates how to write "Hello, world" to a file named myfile.out
in the current directory:
# open and write to a file with ruby open('myfile.out', 'w') { |f| f.puts "Hello, world." }
It's 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
.
It's also very important to note that if that file already existed, this example would have just overwritten the previous file contents.
Ruby write to file - variations
If you like variety in your life there are actually quite a few different ways to write to a file. Here's the same example, with the do/end block syntax:
open('myfile.out', 'w') do |f| f.puts "Hello, world." end
And in this next Ruby example I show how to write to the file using the <<
operator:
open('myfile.out', 'w') do |f| f << "Hello, world.\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.
Ruby file writing - writing multiple lines
Finally, if you want to write more than one line to the file at a time, here's a quick Ruby demo showing that this can be done also:
open('myfile.out', 'w') { |f| f << "Four score\n" f << "and seven\n" f << "years ago\n" }