Programming Ruby

The Pragmatic Programmer's Guide

Previous < Contents ^
Next >
class Dir
Parent: Object
Version: 1.6


[ ] chdir chroot delete entries foreach getwd glob mkdir new open pwd rmdir unlink close each read rewind seek tell

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, page 301.

The directory used in these examples contains the two regular files (config.h and main.rb), the parent directory (..), and the directory itself (.).
Enumerable: collect, detect, each_with_index, entries, find, find_all, grep, include?, map, max, member?, min, reject, select, sort, to_a

class methods
[ ] Dir[ aString ] -> anArray

Returns anArray of filenames found by expanding the pattern given in aString. Note that this pattern is not a regexp (it's closer to a shell glob) and may contain the following metacharacters:

** Matches subdirectories recursively
* Matches zero or more characters
? Matches any single character
[ charSet ] Matches any character from the given set of characters. A range of characters is written as charFrom - charTo. The set may be negated with an initial uparrow (^).
{ opt, opt, ... } Matches any one of the optional strings

Dir["config.?"] ["config.h"]
Dir["*.[a-z][a-z]"] ["main.rb"]
Dir["*.[^r]*"] ["config.h"]
Dir["*.{rb,h}"] ["main.rb", "config.h"]
Dir["*"] ["config.h", "main.rb"]

chdir Dir.chdir( [ aString ] ) -> 0

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. Raises a SystemCallError (probably Errno::ENOENT) if the target directory does not exist.

Dir.chdir("/var/spool/mail") 0
Dir.pwd "/var/spool/mail"

chroot Dir.chroot( aString ) -> 0

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.

Dir.chroot("/production/secure/root") 0
Dir.pwd "/"

delete Dir.delete( aString ) -> 0

Deletes the named directory. Raises a subclass of SystemCallError if the directory isn't empty.

entries Dir.entries( aString ) -> anArray

Returns an array containing all of the filenames in the given directory. Will raise a SystemCallError if the named directory doesn't exist.

Dir.entries("testdir") [".", "..", "config.h", "main.rb"]

foreach Dir.foreach( aString ) {| filename | block }

-> nil

Calls the block once for each entry in the named directory, passing the filename of each entry as a parameter to the block.

Dir.foreach("testdir") {|x| puts("Got " + x) }
Got .
Got ..
Got config.h
Got main.rb

getwd Dir.getwd -> aString

Returns the path to the current working directory of this process as a string.

Dir.chdir("/tmp") 0
Dir.getwd "/tmp"

glob Dir.glob( aString ) -> anArray

Synonym for Dir.[] .

mkdir Dir.mkdir( aString [, anInteger ] ) -> 0

Makes a new directory named by aString, 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 on page 301.

new aString ) -> aDir

Returns a new directory object for the named directory.

open aString ) -> aDir aString ) {| aDir | block } -> nil

With no block, open is a synonym for . If a block is present, it is passed aDir as a parameter. The directory is closed at the end of the block, and returns nil.

pwd Dir.pwd -> aString

Synonym for Dir.getwd .

rmdir Dir.rmdir( aString ) -> true

Synonym for Dir.delete .

unlink Dir.unlink( aString ) -> true

Synonym for Dir.delete .

instance methods
close dir.close -> nil

Closes the directory stream. Any further attempts to access dir will raise an IOError.

d ="testdir")
d.close nil

each dir.each {| | block }

-> dir

Calls the block once for each entry in this directory, passing the filename of each entry as a parameter to the block.

d ="testdir")
d.each  {|x| puts ("Got " + x) }
Got .
Got ..
Got config.h
Got main.rb

read -> aString or nil

Reads the next entry from dir and returns it as a string. Returns nil at the end of the stream.

d ="testdir") "." ".." "config.h"

rewind dir.rewind -> dir

Repositions dir to the first entry.

d ="testdir") "."
d.rewind #<Dir:0x401b5cac> "."

seek anInteger ) -> dir

Seeks to a particular location in dir. anInteger must be a value returned by Dir#tell .

d ="testdir") "."
i = d.tell ".." #<Dir:0x401b5cac> ".."

tell dir.tell -> anInteger

Returns the current position in dir. See also Dir#seek .

d ="testdir")
d.tell 0 "."
d.tell 12

Previous < Contents ^
Next >

Extracted from the book "Programming Ruby - The Pragmatic Programmer's Guide"
Copyright © 2001 by Addison Wesley Longman, Inc. This material may be distributed only subject to the terms and conditions set forth in the Open Publication License, v1.0 or later (the latest version is presently available at

Distribution of substantively modified versions of this document is prohibited without the explicit permission of the copyright holder.

Distribution of the work or derivative of the work in any standard (paper) book form is prohibited unless prior permission is obtained from the copyright holder.