Share this post!

Working With Files and Folders in Ruby

Data processing is a common task in programming. Data can come from many places: files, network, database, etc. In this post you will learn how to work with files and folders in Ruby.

files and folders ruby

How to Read Files With Ruby

The file class allows you to open a file by simply passing in the file name to the open method:

file ="users.txt")

Since File is a sub-class of the IO class, you can work with file objects using IO methods.

For example, using gets you can read one line at a time, and using read you can read the whole file or a specified number of bytes.

# Read the first line
# => "user1\n"

# Go back to the start of the file

# Read the whole file
# => "user1\nuser2\nuser3\n"

# We are done, close the file.

You will need to remember to call close on your file, so the contents are flushed to disk (if you wrote to it) and the file descriptor is made available.

If you want to read the whole file with just one line of code you can use, in this case you don’t need to close the file. There is also a File.write counterpart to this method.

data ="users.txt")
# => "user1\nuser2\nuser3\n"

You can then split the data into an array of lines with the split method.

If you want to process the file one line at a time, you can use the foreach method:

File.foreach("users.txt") { |line| puts line }

This is useful for big files where you don’t want to read the whole file into memory.

Writing to Files

File writing is pretty easy too. When opening a file for writing, you need to add the “w” flag as the second argument."log.txt", "w") { |f| f.write "#{} - User logged in\n" }

This will rewrite the previous file contents. If you want to add to the file, use the “a” (append) flag.

Another way to write data into a file is to use File.write:

File.write("log.txt", "data...")

File & Directory Operations

Other than reading and writing there are other operations you may want to do on files. For example, you may want to know if a file exists or get a list of files for the current directory.

Let’s see a few examples:

# Renaming a file
File.rename("old-name.txt", "new-name.txt")

# File size in bytes

# Does this file already exist?

# Get the file extension, this works even if the file doesn't exists
# => ".txt"

# Get the file name without the directory part
# => "ebook.pdf"

# Get the path for this file, without the file name
# => "/tmp"

# Is this actually a file or a directory?"cats")

The last example makes more sense if we are looping through the contents of a directory listing.

def find_files_in_current_directory
  entries = Dir.entries(".")
  entries.reject { |entry| }

Using Dir.glob you can get a list of all the files that match a certain pattern, here are some examples:

# All files in current directory

# All files containing "spec" in the name

# All ruby files

Documentation Links