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.

Download Free Ruby Ebook

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+).

1
2
3
4
5
6
7
8
9
#!/usr/bin/ruby

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

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.

Flags

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.

Exercises

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