Ruby File Handling
In this tutorial we will learn about File handling in Ruby programming language. We will learn how to read data from a file, write data into a file, append data in an existing file with simple code examples. So let's get started.
Ruby: Reading a File
Reading files are very simple in Ruby than other languages.
This is the content of the file named sample.txt
. Now, we are going to read the contents of this file.
This small piece of code reads the contents of any file. You might be confused that there is no statement about the file name. We can specify the file name in the Command Prompt
while running the program.
We run by: ruby files.rb sample.txt
Here's the output:
This is one method of reading the file. We could also read the file by specifying the name of the file in the program. Like this:
Here, we are opening the file using open
method. Variable file acts as a file handler here. So, for each line we are calling the gets
method using the variable
file and storing it in the variable line and printed using puts
method.
The output of the program is :
Ruby: Writing in a Files
We have to create a File object
using new
method for reading data from files or writing data to files.
Here fil is the file object which is created using the new
method. The new method has two parameters, the first parameter is the name
of the file and the second parameter is the mode
. w
represents write mode to a file. We are using the file object fil
with the print
and puts
method to literally write to the file.
When we are finished, we should always close
the file. It is a good practice to always close
the file when done. If we don't close the file, the file maybe corrupted when we try to open it later sometimes. The data printed using print
and puts
method are stored in the buffer, the buffer is flushed when we close the file.
The output of the program is :
Actually, nothing happens when we execute the program. But when we view the file, the content is written in the file. Here is another example,