ruby can open a file for reading and writing (r+) or writing (w+). This is for files on the hard disk, not on the cloud.

In this article we will cover how to write files in ruby. If you are interested in reading files, see tthe read-file article instead.

Related course:
Learn Rails 5.2: Accelerated Web Development with Ruby on Rails

Write files in ruby

Write file

The ruby program below writes a file from the disk. If the file exists, it will be overwritten (w+). If you want to add to end of the file instead, use (a+).


myFile ="file.txt", "w+")
if myFile
myFile.syswrite("Ruby example of file writing.
puts "Unable to open file!"

This writes the ruby string into the newly created file. If you get an error, it means you don’t have the right user permissions to write a file (no write access) or that the disk is full.

Otherwise the new file has been created (file.txt). This file contains the string contents which you can see with any text editor.


If you use the w+ flag the file will be created if it doesn’t exist. The w+ flag makes ruby overwrite the file if it already exists.

The r+ does the same, but ruby then allows you to read files. Reading files is not allowed with the w+ flag.

If you want to append to a file (add) you can use the a+ flag. This will not overwrite the file, only append the end of the file.


  1. Write a list of cities to a new file.