Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
instance method
Pathname#rename
(::Pathname | ::string new_name) -> 0
rename(new_path) → 0
pathname_builtin.rb
View on GitHub ↗
# File tmp/rubies/ruby-4.1.0-preview1/pathname_builtin.rb, line 1855
def rename(to) File.rename(@path, to) end
Moves the entry at the path in self to the given new_path, which may be either a path or another pathname.
Does not follow symbolic links; if the entry is a symlink, the link itself is renamed.
The examples below use two temporary directories:
Example
pn_srcdir = Pathname('/tmp/src/') # => #<Pathname:/tmp/src/> pn_dstdir = Pathname('/tmp/dst/') # => #<Pathname:/tmp/dst/> pn_srcdir.mkdir pn_dstdir.mkdir
The entry to be renamed may be a file:
Example
# Create source pathname and file. pn_srcfile = pn_srcdir.join('t.tmp') # => #<Pathname:/tmp/src/t.tmp> pn_srcfile.write('foo') # Create destination file pathname. pn_dstfile = pn_dstdir.join('u.tmp') # => #<Pathname:/tmp/dst/u.tmp> # Rename source file as destination file. pn_srcfile.rename(pn_dstfile) pn_srcfile.exist? # => false pn_dstfile.exist? # => true pn_srcfile # => #<Pathname:/tmp/src/t.tmp> # Not changed. pn_dstfile.delete # Clean up.
The entry to be renames may be a symbolic link:
Example
# Create source pathname and file. pn_srcfile = pn_srcdir.join('t.tmp') # => #<Pathname:/tmp/src/t.tmp> pn_srcfile.write('foo') # Create link pathname and link. pn_lnkfile = pn_dstdir.join('u.tmp') pn_lnkfile = pn_dstdir.join('u.tmp') pn_lnkfile.make_symlink(pn_srcfile) pn_lnkfile.readlink # => #<Pathname:/tmp/src/t.tmp> pn_renamed = Pathname('lib/v.tmp') # => #<Pathname:lib/v.tmp> pn_lnkfile.rename(pn_renamed) # Symlink not followed. pn_renamed.symlink? # => true pn_renamed.readlink # => #<Pathname:/tmp/src/t.tmp> pn_lnkfile # => #<Pathname:/tmp/dst/u.tmp> # Not changed. # Clean up. pn_renamed.delete pn_srcfile.delete
The entry to be renamed may be a directory:
Example
pn_renamed = Pathname('/tmp/foo') # => #<Pathname:/tmp/foo> pn_dstdir.rename(pn_renamed)
Clean up:
Example
pn_renamed.rmtree # => #<Pathname:/tmp/foo> pn_srcdir.rmtree # => #<Pathname:/tmp/src/>
Raises SystemCallError if the entry cannot be renamed.