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
file.c
View on GitHub ↗
static VALUE
rb_file_s_rename(VALUE klass, VALUE from, VALUE to)
{
struct rename_args ra;
VALUE f, t;
FilePathValue(from);
FilePathValue(to);
f = rb_str_encode_ospath(from);
t = rb_str_encode_ospath(to);
ra.src = StringValueCStr(f);
ra.dst = StringValueCStr(t);
#if defined __CYGWIN__
errno = 0;
#endif
if (IO_WITHOUT_GVL_INT(no_gvl_rename, &ra) < 0) {
int e = errno;
#if defined DOSISH
switch (e) {
case EEXIST:
if (chmod(ra.dst, 0666) == 0 &&
unlink(ra.dst) == 0 &&
rename(ra.src, ra.dst) == 0)
return INT2FIX(0);
}
#endif
syserr_fail2(e, from, to);
}
return INT2FIX(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.