Ruby Rename Files

Last Updated On Tuesday 25th Jan 2022

Ruby Rename File

A File is an abstraction of any file object accessible by the program and is closely associated with class IO.

Renames the given file to the new name. Raises a SystemCallError if the file cannot be renamed.


	File.rename("afile.txt", "aewfwdf.txt")   #=> 0

Code Example

	File.rename(f, folder_path + "/" + filename.capitalize + File.extname(f))
	File.rename("test.txt", "test1.txt")

Rename Files in Current Folder

	folder_path = "."

files = Dir.entries(folder_path).filter{ |dir| dir.include? "-1.svg" }
p files
files.each do |file|
  filename = File.basename(file, File.extname(file))
  File.rename(file, filename.gsub("-1", "-active") + File.extname(file))