Solution: Rename Files

Go over the implementation of renaming files.

Solution

require 'fileutils'
directory = File.expand_path(File.join(File.dirname(__FILE__), "files"))

Dir.foreach(directory) do |item|
	next if item == '.' or item == '..'
	
	if item =~ /exercise\s(\d+)(.*)/
		new_sequence = $1.rjust(2, "0")
		new_filename = "exercise_" + new_sequence + $2
		
		FileUtils.mv(File.join(directory, item), File.join(directory, new_filename))
	end
end
puts "Files renamed successfully!"
Renaming files in a directory

Explanation

  • Line 1: fileutils is loaded to enable us to use the method mv.

  • Line 7: ...