English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Ruby Dir Class and Methods

Dir is a directory stream used to provide filenames in the directory of the operating system. The Dir class also has operations related to directories, such as wildcard filename matching, changing the working directory, etc.

Class method

NumberMethods & Descriptions
1Dir[pat]
Dir::glob( pat)

Returns an array containing filenames that match the specified wildcard pattern pat:
  • * - Matches any string containing a null string

  • ** - Matches any string recursively

  • ? - Matches any single character

  • [...] - Matches any character within the enclosed characters

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

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 (only allowed for superuser). 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 filenames in the directory path.
6Dir::foreach( path) {| f| ...}
Execute a block for each file in the directory specified by path.
7Dir::getwd
Dir::pwd

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

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

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

Example Method

Assuming d is Dir An example of a class:

NumberMethods & Descriptions
1d.close
Close the directory stream.
2d.each {| f| ...}
Execute a block for each entry in d.
3d.pos
d.tell
Return the current position in d.
4d.pos= offset
Set the position in the directory stream.
5d.pos= pos
d.seek(pos)

Move to a position in d. pos must be a value returned by d.pos or 0.
6d.read
Return 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.