How to Use the Ruby Fileutils Module

09/23/2021

Contents

In this article, you will learn how to use the Ruby Fileutils module.

Using the Ruby Fileutils module

The Ruby FileUtils module provides a set of file utility methods that allow you to manipulate files and directories easily. Here are some ways to use the FileUtils module:

Creating a directory

You can create a new directory using the mkdir method:

require 'fileutils'

FileUtils.mkdir('new_directory')

Copying files

You can copy files from one location to another using the cp method:

FileUtils.cp('source_file', 'destination_file')

You can also copy a directory and all its contents recursively using the cp_r method:

FileUtils.cp_r('source_directory', 'destination_directory')

Moving or renaming files

You can move or rename files using the mv method:

FileUtils.mv('old_name', 'new_name')

You can also move a directory and all its contents recursively using the mv method:

FileUtils.mv('old_directory', 'new_directory')

Removing files or directories

You can delete files using the rm method:

FileUtils.rm('file_to_delete')

You can also delete a directory and all its contents recursively using the rm_r method:

FileUtils.rm_r('directory_to_delete')

Changing file permissions

You can change the permissions of a file using the chmod method:

FileUtils.chmod(0644, 'file_to_change_permissions')

This will set the file’s permissions to rw-r–r–.

Creating a symlink

You can create a symbolic link to a file or directory using the ln_s method:

FileUtils.ln_s('source_file', 'symbolic_link')

Archiving and unarchiving files

You can create a tar archive of a directory using the tar method:

FileUtils.tar('archive.tar', 'directory_to_archive')

You can also extract the contents of a tar archive using the tar_extract method:

FileUtils.tar_extract('archive.tar', 'destination_directory')

These are just some of the many methods available in the FileUtils module. By using this module, you can simplify your file and directory manipulation tasks in your Ruby programs.