rename a file in ruby

To rename a file in Ruby, you can use the File.rename method. This method takes two arguments: the current name of the file and the new name you want to give it.

main.rb
File.rename("old_name.txt", "new_name.txt")
44 chars
2 lines

This will rename the file from "old_name.txt" to "new_name.txt". Note that this method will overwrite the destination file if it already exists. If you want to avoid this, you can use the FileUtils.mv method instead:

main.rb
require 'fileutils'

FileUtils.mv("old_name.txt", "new_name.txt")
66 chars
4 lines

This will also rename the file, but will raise an exception if the destination file already exists. It will also preserve the file's permissions, ownership, and timestamps.

gistlibby LogSnag