Working with files is practically a requirement for any developer. In most instances, if you are not saving data to a database, you are probably saving it to a file.

This guide will show you how to use Ruby I/O methods to open, read, write, and create new files.

Let us start at the basics of Input and Output in Ruby

Basic I/O

The most basic I/O methods in Ruby are the ones we use to print text on the screen.

Puts

The puts method is probably the most common I/O method.

To print something on the screen, simply:

The puts command will print the value stored in the referenced variable and add a new line at the end.

Print

The print method is similar to the puts, but it does not add a trailing new line. It leaves the cursor in the same line.

Putc

Another common basic I/O method is the putc method. It works similarly to the puts and print method, but it prints one character at a time.

For example:

my_var = “Hello World!”

putc my_var

The above should print the character ‘H.’

Gets

The gets method, on the other hand, fetches input from the user using the STDIN stream.

puts “Enter your age: “


age = gets

puts “You are #{age} years old”

File I/O

Although understanding how to work with the standard in and out is helpful, it can be very limiting when you need persistent data.

In such a case, we can use the File Input and Output to read and write to files.

File.New()

The first useful method when working with files is the new method. This creates a new file object with the specified file name and the mode.

The general syntax is:

f = File.new(‘filename’, ‘mode’)

The filename can be any name and extension.

Ruby supports various file modes. These include:

  1. r – Read-Only Mode
  2. w – Write-Only Mode
  3. r – Read-Write Mode
  4. w Read-Write mode
  5. a – Write mode and append new data if the file exists; if not, create file and add the data.
  6. a – Same as “a” but uses the Read-Write mode.

For example, to create a new file that does not exist:

f = File.new(“new.txt”, “a “)


f.syswrite(“I have been recently created”)


f.close()

In the above example, we create a new file object with the name new.txt and the Read-Write mode. Since the file does not exist, it is automatically created.

In the next line, we write to the file using the syswrite method and, finally, close the file.

$ cat new.txt


I have been recently created

File.Open()

You can use the open method to open a file. Once you open a file, you can read or write to it.

For example:

f = File.open(“new.txt”)


content = f.read

puts content

In the above example, we use the open method to open an existing file in the current working directory.

Once opened, we can read the file contents.

Notice that we do not specify the mode when opening the file for reading because it is set to read when unspecified.

To write to a file, you need to specify the mode as the write or read-write as shown in the example below:

f = File.open(“new.txt”, “r “)


f.write(“This is another line”)

f.close()

In the above example, we specify the mode as Read-Write as we are writing to the file.

File.rename()

Besides reading and writing to a file, Ruby allows you to perform other operations, including renaming the file using the rename method.

Example:

f = File.rename(“new.txt”, “renamed.txt”)

The method above should rename the new.txt file to renamed.txt.

File.Delete()

To delete a file, you can use the delete method and specify the filename as the argument. For example:

puts “#{File.delete(“renamed.txt“)} deleted!”

File.dirname()

The dirname method allows you to get the path of the file without including the filename.

For example:

f = File.dirname(“https://linuxhint.com/var/log/lastlog”)

puts f

This should display the full path to the directory where the file is located.

File.exists?

To check if a file exists, use the file.exists? method. It returns a Boolean true if the value exists and false if otherwise.

puts File.exists?(“https://linuxhint.com/etc/passwd”)

true

Directory I/O

If you want to work with Directories in Ruby, you can use the Dir class that contains methods for such operations.

They include:

  1. pwd() – Returns the current working directory
  2. empty?(“/dirpath”) – Checks if a directory is empty
  3. mkdir(“/dirpath”) – Creates a directory with the specified name.
  4. delete(“/dirpath”) – Deletes the specified directory
  5. chdir(“/dirpath”) – Navigates to the specified directory path
  6. entries(“/dirpath”) – Lists all the files in the directory.

Conclusion

This tutorial has shown you how to use various Ruby Input/Output operations. It is good to note that there are other operations you can perform beyond those discussed in this tutorial. Consider the File and Dir class documentation to learn more.

About the author

<img alt="" data-del="avatar" data-lazy-src="https://kirelos.com/wp-content/uploads/2021/08/echo/john-150×150.png61214b53f3128.jpg" height="112" src="data:image/svg xml,” width=”112″>

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list