Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
Dir.chdir
static VALUE
dir_s_chdir(int argc, VALUE *argv, VALUE obj)
{
VALUE path = Qnil;
if (rb_check_arity(argc, 0, 1) == 1) {
path = rb_str_encode_ospath(rb_get_path(argv[0]));
}
else {
const char *dist = getenv("HOME");
if (!dist) {
dist = getenv("LOGDIR");
if (!dist) rb_raise(rb_eArgError, "HOME/LOGDIR not set");
}
path = rb_str_new2(dist);
}
return chdir_path(path, true);
}
Changes the current working directory.
With argument new_dirpath and no block, changes to the given dirpath:
Dir.pwd # => "/example" Dir.chdir('..') # => 0 Dir.pwd # => "/"
With no argument and no block:
-
Changes to the value of environment variable
HOMEif defined. -
Otherwise changes to the value of environment variable
LOGDIRif 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:
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:
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.