In this Cheat sheet, you will learn managing files from Ruby.

Files are used for storing the Data for a Long time Period. And the files can contain any type of information means they can Store the text, any Images or Pictures or any data in any Format. It is associated with class IO File includes.

Creating a New File

New files are created in Ruby using the new method of the File class. The new method accepts two arguments, the first being the name of the file to be created and the second being the mode in which the file is to open. Like,

file =“filename”, “mode”)


Supported modes are:

r Read only access.
r+ Read and write access.
w Write only access.
w+ Read and write access.
a Write only access.
a+ Read and write access.

Opening Existing Files

You can open the existing files using the open method.


If the file is already opened, we can close it by using the close method.


Reading and Writing Files

Once we’ve opened an existing file or created a new file we need to be able to read from and write to that file. We can read/write using different methods.

sysread Method:

You can use the method sysread to read the contents of a file.


This statement will output the first 10 characters of the file.

syswrite Method:

You can use the method syswrite to write the contents into a file.


It writes ‘Hello’ into the file input.txt.

each_byte Method:

This method belongs to the class File. The method each_byte is always associated with a block.


Characters are passed one by one to the variable ch and then displayed on the screen.

IO.readlines Method:

The class File is a subclass of the class IO. This method returns the contents of the file line by line.


Each line of the file input.txt will be an element in the array arr. Therefore, arr[0] will contain the first line, whereas arr[1] will contain the second line of the file.

IO.foreach Method:

This method also returns output line by line. The difference between the method foreach and the method readlines is that the method foreach is associated with a block.


This code will pass the contents of the file test line by line to the variable block, and then the output will be displayed on the screen.

Renaming and Deleting Files

Files are renamed and deleted in Ruby using the rename and delete methods respectively. For example, we can create a new file, rename it and then delete it: