Ruby Dir Class and Methods

DirRepresents a directory stream for giving filenames in directories in the operating system. The Dir class also has directory-related operations, such as wildcard filename matching, changing the working directory, etc.

Class Methods

No.Method & Description
1Dir[pat]
Dir::glob( pat)

Returns an array containing filenames that match the specified wildcard pattern pat:
  • *- Matches any string including null string
  • **- Recursively matches any string
  • ?- Matches any single character
  • [...]- Matches any one of the enclosed characters
  • {a,b...}- Matches any one of the strings
Dir["foo.*"] # matches "foo.c", "foo.rb", etc.
Dir["foo.?"] # matches "foo.c", "foo.h", etc.
2Dir::chdir( path)
Changes the current directory.
3Dir::chroot( path)
Changes the root directory (allowed only for superusers). Not available on all platforms.
4Dir::delete( path)
Deletes the directory specified by path. The directory must be empty.
5Dir::entries( path)
Returns an array containing the filenames in the directory path.
6Dir::foreach( path) {| f| ...}
Executes the block once for each file in the directory specified by path.
7Dir::getwd
Dir::pwd

Returns the current directory.
8Dir::mkdir( path[, mode=0777])
Creates the directory specified by path. The permission mode can be modified by the value of File::umask and is ignored on Win32 platforms.
9Dir::new( path)
Dir::open( path)
Dir::open( path) {| dir| ...}

Returns a new directory object for path. If a block is given to open, the new directory object is passed to the block, and the block closes the directory object before terminating.
10Dir::pwd
See Dir::getwd.
11Dir::rmdir( path)
Dir::unlink( path)
Dir::delete( path)

Deletes the directory specified by path. The directory must be empty.

Instance Methods

AssumedYesDirAn instance of the class:

No.Method & Description
1d.close
Closes the directory stream.
2d.each {| f| ...}
Executes the block once for each entry in d.
3d.pos
d.tell
Returns the current position in d.
4d.pos= offset
Sets the position in the directory stream.
5d.pos= pos
d.seek(pos)

Moves to a position in d. pos must be a value returned by d.pos or 0.
6d.read
Returns the next entry in d.
7d.rewind
Moves the position in d to the first entry.
8d.seek(po s)
See d.pos=pos.
9d.tell
See d.pos.
Other Extensions