Rename files with ruby. Once you have a file in a directory you can simply rename it from your code.

The file will be renamed in the same directory. If you want to rename and move it to a new directory, change the variable to_file.

Download Free Ruby Ebook

Rename file in ruby

Example

The program below renames an existing file. Make sure the file exists before running the file. You can simply create an empty file.

1
2
3
4
5
6
7
8
9
10
11
12
#!/usr/bin/ruby -w

# get current directory
folder_path = Dir.pwd
filename = "hello.mp3"

# source and destination file
from_file = folder_path + "/" + filename
new_file = from_file + ".txt"

# rename file
File.rename(from_file, new_file)

The file defined by the variable from_file will be renamed to the filename new_file.

Run program with the command:

1
ruby rename.rb

The file will be renamed to a new file.

Rename in shell

Now there are other ways to do this, for example on a Linux or Mac OS X system you can run the command

1
mv source.txt destination.txt

But this may or may not work on other platforms. Thats why you should always use the modules provides by the programming language.