Rename Files
Learn about regular expressions in Ruby and use them to rename files in a directory.
Problem
Write a program to rename the following files in a directory, so that the files are always shown in alphabetical order and without spaces:
Order in which files are listed
Before | After |
exercise 1.txt | exercise_01.txt |
exercise 10.txt | exercise_02.txt |
exercise 11.txt | exercise_03.txt |
exercise 2.txt | exercise_04.txt |
exercise 3.txt | exercise_05.txt |
exercise 4.txt | exercise_06.txt |
exercise 5.txt | exercise_07.txt |
exercise 6.txt | exercise_08.txt |
exercise 7.txt | exercise_09.txt |
exercise 8.txt | exercise_10.txt |
exercise 9.txt | exercise_11.txt |
The above sample files can be found in the files
directory, which is present in the same directory as your program.
Purpose
Process files in a directory
Use regular expressions for pattern matching
Rename files
Analyze
The objective is quite clear, and can be divided into the following steps:
  1. Iterate over each file in the specified directory (by path).
  2. Extract the single-digit number from the original file name, e.g.,