Skip to content

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

class method

Dir.chdir

(?::path dir) -> 0
[U] (?::path dir) { (::String dir) -> U } -> U
Dir.chdir(new_dirpath) → 0
Dir.chdir → 0
Dir.chdir(new_dirpath) {|new_dirpath| ... } → object
Dir.chdir {|cur_dirpath| ... } → object

Changes the current working directory.

With argument new_dirpath and no block, changes to the given dirpath:

Example
Dir.pwd         # => "/example"
Dir.chdir('..') # => 0
Dir.pwd         # => "/"

With no argument and no block:

  • Changes to the value of environment variable HOME if defined.

  • Otherwise changes to the value of environment variable LOGDIR if defined.

  • Otherwise makes no change.

With argument new_dirpath and a block, temporarily changes the working directory:

  • Calls the block with the argument.

  • Changes to the given directory.

  • Executes the block (yielding the new path).

  • Restores the previous working directory.

  • Returns the block’s return value.

Example:

Example
Dir.chdir('/var/spool/mail')
Dir.pwd   # => "/var/spool/mail"
Dir.chdir('/tmp') do
  Dir.pwd # => "/tmp"
end
Dir.pwd   # => "/var/spool/mail"

With no argument and a block, calls the block with the current working directory (string) and returns the block’s return value.

Calls to Dir.chdir with blocks may be nested:

Example
Dir.chdir('/var/spool/mail')
Dir.pwd     # => "/var/spool/mail"
Dir.chdir('/tmp') do
  Dir.pwd   # => "/tmp"
  Dir.chdir('/usr') do
    Dir.pwd # => "/usr"
  end
  Dir.pwd   # => "/tmp"
end
Dir.pwd     # => "/var/spool/mail"

In a multi-threaded program an error is raised if a thread attempts to open a chdir block while another thread has one open, or a call to chdir without a block occurs inside a block passed to chdir (even in the same thread).

Raises an exception if the target directory does not exist.

See also #chdir .[] .children .chroot also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0