Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

class method

File.rename

(::path old_name, ::path new_name) -> 0
File.rename(path, new_path) → 0

Moves the entry at the given path to the given new_path.

Does not follow symbolic links; if the entry is a symlink, the link itself is renamed.

The examples below use two temporary directories:

Example
src_dirpath = '/tmp/src/' # => "/tmp/src/"
dst_dirpath = '/tmp/dst/' # => "/tmp/dst/"
Dir.mkdir(src_dirpath)
Dir.mkdir(dst_dirpath)

The entry to be renamed may be a file:

Example
src_filepath = File.join(src_dirpath, 't.tmp') # => "/tmp/src/t.tmp"
File.write(src_filepath, 'foo')
dst_filepath = File.join(dst_dirpath, 'u.tmp') # => "/tmp/dst/u.tmp"
File.rename(src_filepath, dst_filepath)
File.exist?(src_filepath)                      # => false
File.exist?(dst_filepath)                      # => true
File.delete(dst_filepath)                      # Clean up.

The entry to be renamed may be a symbolic link:

Example
filepath = File.join(src_dirpath, 't.tmp') # => "/tmp/src/t.tmp"
File.write(src_filepath, 'foo')
linkpath = File.join(src_dirpath, 'u.tmp') # => "/tmp/src/u.tmp"
File.symlink(filepath, linkpath)
File.readlink(linkpath)                    # => "/tmp/src/t.tmp"
newpath = File.join(dst_dirpath, 'v.tmp')  # => "/tmp/dst/v.tmp"
File.rename(linkpath, newpath)             # Symlink not followed.
File.readlink(newpath)                     # => "/tmp/src/t.tmp"
File.delete(filepath, newpath)             # Clean up.

The entry to be renamed may be a directory:

Example
old_dirpath = File.join(src_dirpath, 'olddir') # => "/tmp/src/olddir"
Dir.mkdir(old_dirpath)
new_dirpath = File.join(dst_dirpath, 'newdir') # => "/tmp/dst/newdir"
File.rename(old_dirpath, new_dirpath)
File.directory?(new_dirpath)                   # => true
Dir.rmdir(new_dirpath)                         # Clean up.

Clean up:

Example
FileUtils.rm_rf(src_dirpath) # => ["/tmp/src/"]
FileUtils.rm_rf(dst_dirpath)  # => ["/tmp/dst/"]

Raises SystemCallError if the file cannot be renamed.

See also .realpath .setgid? .realdirpath .setuid? also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0