How to Change Filenames in Ruby



In this article, you will learn how to change filenames in Ruby.

Changing filenames in Ruby

In Ruby, there are several ways to change filenames. Here are three methods to achieve this:

Using the File.rename method

The simplest way to change a filename is to use the built-in File.rename method in Ruby. This method takes two arguments: the current filename and the new filename.

File.rename("old_file_name.txt", "new_file_name.txt")

In this example, the file “old_file_name.txt” will be renamed to “new_file_name.txt”.

Using the method

Another way to rename a file in Ruby is to use the method. This method is part of the FileUtils module, which provides a set of file-related utility methods.

require 'fileutils'"old_file_name.txt", "new_file_name.txt")

In this example, we first require the fileutils module and then call the method to rename the file.

Using the Dir.glob method

If you want to rename multiple files that match a certain pattern, you can use the Dir.glob method to find the files and then rename them using one of the methods described above.

Dir.glob("*.txt").each do |file_name|
  new_name = file_name.gsub(/old_text/, "new_text")
  File.rename(file_name, new_name)

In this example, we use Dir.glob to find all files with the “.txt” extension in the current directory. We then loop over each file, replacing the text “old_text” with “new_text” in the filename, and then rename the file using the File.rename method.