Dir

The Dir class is used to interact with directories in the file system. Like many of Ruby’s file manipulation classes, it has both a lot of class methods and instance methods, in some cases duplicating functionality.

You create a Dir instance with Dir.new(path), where the path is a string or something that can be implicitly converted to a string because it implements to_str (so Pathname objects can be used here). The path is relative to the current system working directory. There’s an optional keyword argument, encoding:, which specifies the encoding of the directory as you look at it.

Directories can technically be opened and closed in Ruby; when open, they stream a list of their children files. The class method Dir.open(path) {|dir|} ...

Get Programming Ruby 3.3 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.