Ruby Dir classes and methods


Dir is a directory stream representing the names of files in a directory within the operating system. The Dir class also has directory-related operations, such as wildcard file name matching, changing the working directory, etc.

Class Method

Serial NumberMethod & Description
1Dir[pat]
Dir::glob(pat)

Returns an array containing file names matching the specified wildcard pattern pat:
  • * - Matches any string that contains the null string

  • ** - Matches any string recursively

  • ? - Matches any single character

  • [...] - Matches any one of the enclosed characters

  • {a,b...} - Matches any one in the string

Dir["foo.*"] # Match "foo.c", "foo.rb", etc.
Dir["foo.?"] # Match "foo.c", "foo.h", etc.
2Dir::chdir(path)
Change the current directory.
3Dir::chroot( path)
Change the root directory (only superuser allowed). Not available on all platforms.
4Dir::delete( path)
Delete the directory specified by path. The directory must be empty.
5Dir::entries( path)
Returns an array containing the file names in the directory path.
6Dir::foreach( path) {| f| ...}
In the directory specified by path Blocks are executed once per file.
7Dir::getwd
Dir::pwd

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

Returns the new directory object of path. If open is given a block, new directory objects are 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)

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

Instance method

Assume d is an instance of the Dir class:

Serial number Method & Description
1d.close
Close the directory stream.
2d.each {| f| ...}
Execute the block once for each entry in d.
3d.pos
d.tell
Returns the current position in d.
4d.pos= offset
Set the position in the directory stream.
5d.pos= pos
d.seek(pos)

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