Method: Dir.chdir
- Defined in:
- dir.c
.chdir(new_dirpath) ⇒ 0 .chdir ⇒ 0 .chdir(new_dirpath) {|new_dirpath| ... } ⇒ Object .chdir {|cur_dirpath| ... } ⇒ Object
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.
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 |
# File 'dir.c', line 1301 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); } |