class Dir
Objects of class Dir
are directory streams representing directories in the underlying file system. They provide a variety of ways to list directories and their contents. See also File
.
The directory used in these examples contains the two regular files (config.h
and main.rb
), the parent directory (..
), and the directory itself (.
).
What’s Here¶ ↑
First, what’s elsewhere. Class Dir:
-
Inherits from class Object.
-
Includes module Enumerable, which provides dozens of additional methods.
Here, class Dir provides methods that are useful for:
Reading¶ ↑
close
-
Closes the directory stream for
self
.
pos=
-
Sets the position in the directory stream for
self
.
read
-
Reads and returns the next entry in the directory stream for
self
.
rewind
-
Sets the position in the directory stream for
self
to the first entry.
seek
-
Sets the position in the directory stream for
self
the entry at the given offset.
Setting¶ ↑
::chdir
-
Changes the working directory of the current process to the given directory.
::chroot
-
Changes the file-system root for the current process to the given directory.
Querying¶ ↑
::children
-
Returns an array of names of the children (both files and directories) of the given directory, but not including
.
or..
.
::empty?
-
Returns whether the given path is an empty directory.
::entries
-
Returns an array of names of the children (both files and directories) of the given directory, including
.
and..
.
::exist?
-
Returns whether the given path is a directory.
::getwd
(aliased as pwd)-
Returns the path to the current working directory.
::glob
-
Returns an array of file paths matching the given pattern and flags.
::home
-
Returns the home directory path for a given user or the current user.
children
-
Returns an array of names of the children (both files and directories) of
self
, but not including.
or..
.
fileno
-
Returns the integer file descriptor for
self
.
Iterating¶ ↑
::each_child
-
Calls the given block with each entry in the given directory, but not including
.
or..
.
::foreach
-
Calls the given block with each entryin the given directory, including
.
and..
.
each
-
Calls the given block with each entry in
self
, including.
and..
.
each_child
-
Calls the given block with each entry in
self
, but not including.
or..
.
Other¶ ↑
Public Class Methods
Equivalent to calling Dir.glob([
string,…], 0)
.
# File dir.rb, line 127 def self.[](*args, base: nil, sort: true) Primitive.dir_s_aref(args, base, sort) end
Changes the current working directory of the process to the given string. When called without an argument, changes the directory to the value of the environment variable HOME
, or LOGDIR
. SystemCallError
(probably Errno::ENOENT) if the target directory does not exist.
If a block is given, it is passed the name of the new current directory, and the block is executed with that as the current directory. The original working directory is restored when the block exits. The return value of chdir
is the value of the block. chdir
blocks can be nested, but in a multi-threaded program an error will be 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).
Dir.chdir("/var/spool/mail") puts Dir.pwd Dir.chdir("/tmp") do puts Dir.pwd Dir.chdir("/usr") do puts Dir.pwd end puts Dir.pwd end puts Dir.pwd
produces:
/var/spool/mail /tmp /usr /tmp /var/spool/mail
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); } if (chdir_blocking > 0) { if (rb_thread_current() != chdir_thread) rb_raise(rb_eRuntimeError, "conflicting chdir during another chdir block"); if (!rb_block_given_p()) rb_warn("conflicting chdir during another chdir block"); } if (rb_block_given_p()) { struct chdir_data args; args.old_path = rb_str_encode_ospath(rb_dir_getwd()); args.new_path = path; args.done = FALSE; return rb_ensure(chdir_yield, (VALUE)&args, chdir_restore, (VALUE)&args); } else { char *p = RSTRING_PTR(path); int r = (int)(VALUE)rb_thread_call_without_gvl(nogvl_chdir, p, RUBY_UBF_IO, 0); if (r < 0) rb_sys_fail_path(path); } return INT2FIX(0); }
Returns an array containing all of the filenames except for “.” and “..” in the given directory. Will raise a SystemCallError
if the named directory doesn’t exist.
The optional encoding keyword argument specifies the encoding of the directory. If not specified, the filesystem encoding is used.
Dir.children("testdir") #=> ["config.h", "main.rb"]
static VALUE dir_s_children(int argc, VALUE *argv, VALUE io) { VALUE dir; dir = dir_open_dir(argc, argv); return rb_ensure(dir_collect_children, dir, dir_close, dir); }
Changes this process’s idea of the file system root. Only a privileged process may make this call. Not available on all platforms. On Unix systems, see chroot(2)
for more information.
static VALUE dir_s_chroot(VALUE dir, VALUE path) { path = check_dirname(path); if (chroot(RSTRING_PTR(path)) == -1) rb_sys_fail_path(path); return INT2FIX(0); }
Deletes the named directory. Raises a subclass of SystemCallError
if the directory isn’t empty.
static VALUE dir_s_rmdir(VALUE obj, VALUE dir) { const char *p; int r; dir = check_dirname(dir); p = RSTRING_PTR(dir); r = (int)(VALUE)rb_thread_call_without_gvl(nogvl_rmdir, (void *)p, RUBY_UBF_IO, 0); if (r < 0) rb_sys_fail_path(dir); return INT2FIX(0); }
Calls the block once for each entry except for “.” and “..” in the named directory, passing the filename of each entry as a parameter to the block.
If no block is given, an enumerator is returned instead.
Dir.each_child("testdir") {|x| puts "Got #{x}" }
produces:
Got config.h Got main.rb
static VALUE dir_s_each_child(int argc, VALUE *argv, VALUE io) { VALUE dir; RETURN_ENUMERATOR(io, argc, argv); dir = dir_open_dir(argc, argv); rb_ensure(dir_each_child, dir, dir_close, dir); return Qnil; }
Returns true
if the named file is an empty directory, false
if it is not a directory or non-empty.
static VALUE rb_dir_s_empty_p(VALUE obj, VALUE dirname) { VALUE result, orig; const char *path; enum {false_on_notdir = 1}; FilePathValue(dirname); orig = rb_str_dup_frozen(dirname); dirname = rb_str_encode_ospath(dirname); dirname = rb_str_dup_frozen(dirname); path = RSTRING_PTR(dirname); #if defined HAVE_GETATTRLIST && defined ATTR_DIR_ENTRYCOUNT { u_int32_t attrbuf[SIZEUP32(fsobj_tag_t)]; struct attrlist al = {ATTR_BIT_MAP_COUNT, 0, ATTR_CMN_OBJTAG,}; if (getattrlist(path, &al, attrbuf, sizeof(attrbuf), 0) != 0) rb_sys_fail_path(orig); if (*(const fsobj_tag_t *)(attrbuf+1) == VT_HFS) { al.commonattr = 0; al.dirattr = ATTR_DIR_ENTRYCOUNT; if (getattrlist(path, &al, attrbuf, sizeof(attrbuf), 0) == 0) { if (attrbuf[0] >= 2 * sizeof(u_int32_t)) return attrbuf[1] ? Qfalse : Qtrue; if (false_on_notdir) return Qfalse; } rb_sys_fail_path(orig); } } #endif result = (VALUE)rb_thread_call_without_gvl(nogvl_dir_empty_p, (void *)path, RUBY_UBF_IO, 0); if (result == Qundef) { rb_sys_fail_path(orig); } return result; }
Returns an array containing all of the filenames in the given directory. Will raise a SystemCallError
if the named directory doesn’t exist.
The optional encoding keyword argument specifies the encoding of the directory. If not specified, the filesystem encoding is used.
Dir.entries("testdir") #=> [".", "..", "config.h", "main.rb"]
static VALUE dir_entries(int argc, VALUE *argv, VALUE io) { VALUE dir; dir = dir_open_dir(argc, argv); return rb_ensure(dir_collect, dir, dir_close, dir); }
Returns true
if the named file is a directory, false
otherwise.
VALUE rb_file_directory_p(void) { }
Calls the block once for each entry in the named directory, passing the filename of each entry as a parameter to the block.
If no block is given, an enumerator is returned instead.
Dir.foreach("testdir") {|x| puts "Got #{x}" }
produces:
Got . Got .. Got config.h Got main.rb
static VALUE dir_foreach(int argc, VALUE *argv, VALUE io) { VALUE dir; RETURN_ENUMERATOR(io, argc, argv); dir = dir_open_dir(argc, argv); rb_ensure(dir_each, dir, dir_close, dir); return Qnil; }
Returns the path to the current working directory of this process as a string.
Dir.chdir("/tmp") #=> 0 Dir.getwd #=> "/tmp" Dir.pwd #=> "/tmp"
static VALUE dir_s_getwd(VALUE dir) { return rb_dir_getwd(); }
Expands pattern
, which is a pattern string or an Array
of pattern strings, and returns an array containing the matching filenames. If a block is given, calls the block once for each matching filename, passing the filename as a parameter to the block.
The optional base
keyword argument specifies the base directory for interpreting relative pathnames instead of the current working directory. As the results are not prefixed with the base directory name in this case, you will need to prepend the base directory name if you want real paths.
The results which matched single wildcard or character set are sorted in binary ascending order, unless false
is given as the optional sort
keyword argument. The order of an Array
of pattern strings and braces are preserved.
Note that the pattern is not a regexp, it’s closer to a shell glob. See File::fnmatch
for the meaning of the flags
parameter. Case sensitivity depends on your system (File::FNM_CASEFOLD
is ignored).
*
-
Matches any file. Can be restricted by other values in the glob. Equivalent to
/.*/mx
in regexp.*
-
Matches all files
c*
-
Matches all files beginning with
c
*c
-
Matches all files ending with
c
*c*
-
Match all files that have
c
in them (including at the beginning or end).
Note, this will not match Unix-like hidden files (dotfiles). In order to include those in the match results, you must use the File::FNM_DOTMATCH flag or something like
"{*,.*}"
. **
-
Matches directories recursively if followed by
/
. If this path segment contains any other characters, it is the same as the usual*
. ?
-
Matches any one character. Equivalent to
/.{1}/
in regexp. [set]
-
Matches any one character in
set
. Behaves exactly like character sets inRegexp
, including set negation ([^a-z]
). {p,q}
-
Matches either literal
p
or literalq
. Equivalent to pattern alternation in regexp.Matching literals may be more than one character in length. More than two literals may be specified.
\
-
Escapes the next metacharacter.
Note that this means you cannot use backslash on windows as part of a glob, i.e.
Dir["c:\foo*"]
will not work, useDir["c:/foo*"]
instead.
Examples:
Dir["config.?"] #=> ["config.h"] Dir.glob("config.?") #=> ["config.h"] Dir.glob("*.[a-z][a-z]") #=> ["main.rb"] Dir.glob("*.[^r]*") #=> ["config.h"] Dir.glob("*.{rb,h}") #=> ["main.rb", "config.h"] Dir.glob("*") #=> ["config.h", "main.rb"] Dir.glob("*", File::FNM_DOTMATCH) #=> [".", "config.h", "main.rb"] Dir.glob(["*.rb", "*.h"]) #=> ["main.rb", "config.h"] Dir.glob("**/*.rb") #=> ["main.rb", # "lib/song.rb", # "lib/song/karaoke.rb"] Dir.glob("**/*.rb", base: "lib") #=> ["song.rb", # "song/karaoke.rb"] Dir.glob("**/lib") #=> ["lib"] Dir.glob("**/lib/**/*.rb") #=> ["lib/song.rb", # "lib/song/karaoke.rb"] Dir.glob("**/lib/*.rb") #=> ["lib/song.rb"]
# File dir.rb, line 219 def self.glob(pattern, _flags = 0, flags: _flags, base: nil, sort: true) Primitive.dir_s_glob(pattern, flags, base, sort) end
Returns the home directory of the current user or the named user if given.
static VALUE dir_s_home(int argc, VALUE *argv, VALUE obj) { VALUE user; const char *u = 0; rb_check_arity(argc, 0, 1); user = (argc > 0) ? argv[0] : Qnil; if (!NIL_P(user)) { SafeStringValue(user); rb_must_asciicompat(user); u = StringValueCStr(user); if (*u) { return rb_home_dir_of(user, rb_str_new(0, 0)); } } return rb_default_home_dir(rb_str_new(0, 0)); }
Makes a new directory named by string, with permissions specified by the optional parameter anInteger. The permissions may be modified by the value of File::umask
, and are ignored on NT. Raises a SystemCallError
if the directory cannot be created. See also the discussion of permissions in the class documentation for File
.
Dir.mkdir(File.join(Dir.home, ".foo"), 0700) #=> 0
static VALUE dir_s_mkdir(int argc, VALUE *argv, VALUE obj) { struct mkdir_arg m; VALUE path, vmode; int r; if (rb_scan_args(argc, argv, "11", &path, &vmode) == 2) { m.mode = NUM2MODET(vmode); } else { m.mode = 0777; } path = check_dirname(path); m.path = RSTRING_PTR(path); r = (int)(VALUE)rb_thread_call_without_gvl(nogvl_mkdir, &m, RUBY_UBF_IO, 0); if (r < 0) rb_sys_fail_path(path); return INT2FIX(0); }
Dir.mktmpdir
creates a temporary directory.
The directory is created with 0700 permission. Application should not change the permission to make the temporary directory accessible from other users.
The prefix and suffix of the name of the directory is specified by the optional first argument, prefix_suffix.
-
If it is not specified or nil, “d” is used as the prefix and no suffix is used.
-
If it is a string, it is used as the prefix and no suffix is used.
-
If it is an array, first element is used as the prefix and second element is used as a suffix.
Dir.mktmpdir {|dir| dir is ".../d..." } Dir.mktmpdir("foo") {|dir| dir is ".../foo..." } Dir.mktmpdir(["foo", "bar"]) {|dir| dir is ".../foo...bar" }
The directory is created under Dir.tmpdir
or the optional second argument tmpdir if non-nil value is given.
Dir.mktmpdir {|dir| dir is "#{Dir.tmpdir}/d..." } Dir.mktmpdir(nil, "/var/tmp") {|dir| dir is "/var/tmp/d..." }
If a block is given, it is yielded with the path of the directory. The directory and its contents are removed using FileUtils.remove_entry
before Dir.mktmpdir
returns. The value of the block is returned.
Dir.mktmpdir {|dir| # use the directory... open("#{dir}/foo", "w") { something using the file } }
If a block is not given, The path of the directory is returned. In this case, Dir.mktmpdir
doesn’t remove the directory.
dir = Dir.mktmpdir begin # use the directory... open("#{dir}/foo", "w") { something using the file } ensure # remove the directory. FileUtils.remove_entry dir end
# File lib/tmpdir.rb, line 88 def self.mktmpdir(prefix_suffix=nil, *rest, **options) base = nil path = Tmpname.create(prefix_suffix || "d", *rest, **options) {|path, _, _, d| base = d mkdir(path, 0700) } if block_given? begin yield path.dup ensure unless base stat = File.stat(File.dirname(path)) if stat.world_writable? and !stat.sticky? raise ArgumentError, "parent directory is world writable but not sticky" end end FileUtils.remove_entry path end else path end end
Returns a new directory object for the named directory.
The optional encoding keyword argument specifies the encoding of the directory. If not specified, the filesystem encoding is used.
# File dir.rb, line 118 def initialize(name, encoding: nil) Primitive.dir_initialize(name, encoding) end
The optional encoding keyword argument specifies the encoding of the directory. If not specified, the filesystem encoding is used.
With no block, open
is a synonym for Dir::new
. If a block is present, it is passed aDir as a parameter. The directory is closed at the end of the block, and Dir::open
returns the value of the block.
# File dir.rb, line 97 def self.open(name, encoding: nil, &block) dir = Primitive.dir_s_open(name, encoding) if block begin yield dir ensure Primitive.dir_s_close(dir) end else dir end end
Returns the path to the current working directory of this process as a string.
Dir.chdir("/tmp") #=> 0 Dir.getwd #=> "/tmp" Dir.pwd #=> "/tmp"
static VALUE dir_s_getwd(VALUE dir) { return rb_dir_getwd(); }
Deletes the named directory. Raises a subclass of SystemCallError
if the directory isn’t empty.
static VALUE dir_s_rmdir(VALUE obj, VALUE dir) { const char *p; int r; dir = check_dirname(dir); p = RSTRING_PTR(dir); r = (int)(VALUE)rb_thread_call_without_gvl(nogvl_rmdir, (void *)p, RUBY_UBF_IO, 0); if (r < 0) rb_sys_fail_path(dir); return INT2FIX(0); }
Returns the operating system’s temporary file path.
# File lib/tmpdir.rb, line 21 def self.tmpdir tmp = nil ['TMPDIR', 'TMP', 'TEMP', ['system temporary path', @@systmpdir], ['/tmp']*2, ['.']*2].each do |name, dir = ENV[name]| next if !dir dir = File.expand_path(dir) stat = File.stat(dir) rescue next case when !stat.directory? warn "#{name} is not a directory: #{dir}" when !stat.writable? warn "#{name} is not writable: #{dir}" when stat.world_writable? && !stat.sticky? warn "#{name} is world-writable: #{dir}" else tmp = dir break end end raise ArgumentError, "could not find a temporary directory" unless tmp tmp end
Deletes the named directory. Raises a subclass of SystemCallError
if the directory isn’t empty.
static VALUE dir_s_rmdir(VALUE obj, VALUE dir) { const char *p; int r; dir = check_dirname(dir); p = RSTRING_PTR(dir); r = (int)(VALUE)rb_thread_call_without_gvl(nogvl_rmdir, (void *)p, RUBY_UBF_IO, 0); if (r < 0) rb_sys_fail_path(dir); return INT2FIX(0); }
Public Instance Methods
Returns an array containing all of the filenames except for “.” and “..” in this directory.
d = Dir.new("testdir") d.children #=> ["config.h", "main.rb"]
static VALUE dir_collect_children(VALUE dir) { VALUE ary = rb_ary_new(); dir_each_entry(dir, rb_ary_push, ary, TRUE); return ary; }
Closes the directory stream. Calling this method on closed Dir
object is ignored since Ruby 2.3.
d = Dir.new("testdir") d.close #=> nil
static VALUE dir_close(VALUE dir) { struct dir_data *dirp; dirp = dir_get(dir); if (!dirp->dir) return Qnil; closedir(dirp->dir); dirp->dir = NULL; return Qnil; }
Calls the block once for each entry in this directory, passing the filename of each entry as a parameter to the block.
If no block is given, an enumerator is returned instead.
d = Dir.new("testdir") d.each {|x| puts "Got #{x}" }
produces:
Got . Got .. Got config.h Got main.rb
static VALUE dir_each(VALUE dir) { RETURN_ENUMERATOR(dir, 0, 0); return dir_each_entry(dir, dir_yield, Qnil, FALSE); }
Calls the block once for each entry except for “.” and “..” in this directory, passing the filename of each entry as a parameter to the block.
If no block is given, an enumerator is returned instead.
d = Dir.new("testdir") d.each_child {|x| puts "Got #{x}" }
produces:
Got config.h Got main.rb
static VALUE dir_each_child_m(VALUE dir) { RETURN_ENUMERATOR(dir, 0, 0); return dir_each_entry(dir, dir_yield, Qnil, TRUE); }
Returns the file descriptor used in dir.
d = Dir.new("..") d.fileno #=> 8
This method uses dirfd() function defined by POSIX 2008. NotImplementedError
is raised on other platforms, such as Windows, which doesn’t provide the function.
static VALUE dir_fileno(VALUE dir) { struct dir_data *dirp; int fd; GetDIR(dir, dirp); fd = dirfd(dirp->dir); if (fd == -1) rb_sys_fail("dirfd"); return INT2NUM(fd); }
Return a string describing this Dir
object.
static VALUE dir_inspect(VALUE dir) { struct dir_data *dirp; TypedData_Get_Struct(dir, struct dir_data, &dir_data_type, dirp); if (!NIL_P(dirp->path)) { VALUE str = rb_str_new_cstr("#<"); rb_str_append(str, rb_class_name(CLASS_OF(dir))); rb_str_cat2(str, ":"); rb_str_append(str, dirp->path); rb_str_cat2(str, ">"); return str; } return rb_funcallv(dir, idTo_s, 0, 0); }
Returns the path parameter passed to dir’s constructor.
d = Dir.new("..") d.path #=> ".."
static VALUE dir_path(VALUE dir) { struct dir_data *dirp; TypedData_Get_Struct(dir, struct dir_data, &dir_data_type, dirp); if (NIL_P(dirp->path)) return Qnil; return rb_str_dup(dirp->path); }
Returns the current position in dir. See also Dir#seek
.
d = Dir.new("testdir") d.tell #=> 0 d.read #=> "." d.tell #=> 12
Synonym for Dir#seek
, but returns the position parameter.
d = Dir.new("testdir") #=> #<Dir:0x401b3c40> d.read #=> "." i = d.pos #=> 12 d.read #=> ".." d.pos = i #=> 12 d.read #=> ".."
static VALUE dir_set_pos(VALUE dir, VALUE pos) { dir_seek(dir, pos); return pos; }
Reads the next entry from dir and returns it as a string. Returns nil
at the end of the stream.
d = Dir.new("testdir") d.read #=> "." d.read #=> ".." d.read #=> "config.h"
static VALUE dir_read(VALUE dir) { struct dir_data *dirp; struct dirent *dp; GetDIR(dir, dirp); errno = 0; if ((dp = READDIR(dirp->dir, dirp->enc)) != NULL) { return rb_external_str_new_with_enc(dp->d_name, NAMLEN(dp), dirp->enc); } else { int e = errno; if (e != 0) rb_syserr_fail(e, 0); return Qnil; /* end of stream */ } }
Repositions dir to the first entry.
d = Dir.new("testdir") d.read #=> "." d.rewind #=> #<Dir:0x401b3fb0> d.read #=> "."
static VALUE dir_rewind(VALUE dir) { struct dir_data *dirp; GetDIR(dir, dirp); rewinddir(dirp->dir); return dir; }
Seeks to a particular location in dir. integer must be a value returned by Dir#tell
.
d = Dir.new("testdir") #=> #<Dir:0x401b3c40> d.read #=> "." i = d.tell #=> 12 d.read #=> ".." d.seek(i) #=> #<Dir:0x401b3c40> d.read #=> ".."
static VALUE dir_seek(VALUE dir, VALUE pos) { struct dir_data *dirp; long p = NUM2LONG(pos); GetDIR(dir, dirp); seekdir(dirp->dir, p); return dir; }
Returns the current position in dir. See also Dir#seek
.
d = Dir.new("testdir") d.tell #=> 0 d.read #=> "." d.tell #=> 12
static VALUE dir_tell(VALUE dir) { struct dir_data *dirp; long pos; GetDIR(dir, dirp); pos = telldir(dirp->dir); return rb_int2inum(pos); }
Returns the path parameter passed to dir’s constructor.
d = Dir.new("..") d.path #=> ".."