class Dir

An object of class Dir represents a directory in the underlying file system.

It consists mainly of:

About the Examples

Some examples on this page use this simple file tree:

example/
├── config.h
├── lib/
│   ├── song/
│   │   └── karaoke.rb
│   └── song.rb
└── main.rb

Others use the file tree for the Ruby project itself.

Dir As Array-Like

A Dir object is in some ways array-like:

Dir As Stream-Like

A Dir object is in some ways stream-like.

The stream is initially open for reading, but may be closed manually (using method close), and will be closed on block exit if created by Dir.open called with a block. The closed stream may not be further manipulated, and may not be reopened.

The stream has a position, which is the index of an entry in the directory:

Examples (using the simple file tree):

dir = Dir.new('example') # => #<Dir:example>
dir.pos                  # => 0

dir.read # => "."
dir.read # => ".."
dir.read # => "config.h"
dir.read # => "lib"
dir.read # => "main.rb"
dir.pos  # => 5
dir.read # => nil
dir.pos  # => 5

dir.rewind # => #<Dir:example>
dir.pos    # => 0

dir.pos = 3 # => 3
dir.pos     # => 3

dir.seek(4) # => #<Dir:example>
dir.pos     # => 4

dir.close # => nil
dir.read  # Raises IOError.

What’s Here

First, what’s elsewhere. Class Dir:

Here, class Dir provides methods that are useful for:

Reading

Setting

Querying

Iterating

Other