How to Get All Directories in Ruby



In this article, you will learn how to get all directories in Ruby.

Getting all directories in Ruby

In Ruby, you can use the Dir class to get all directories in a given directory. Here’s an example code snippet that shows how to do this:

def get_all_directories(path)
  directories = []
  Dir.foreach(path) do |filename|
    next if filename == '.' || filename == '..'
    if, filename))
      directories << filename

This code defines a method get_all_directories that takes a path argument, which is the directory for which you want to get all subdirectories. It initializes an empty array directories and uses the Dir.foreach method to loop over all files and directories in the specified path.

For each file or directory, it checks if it is not the current directory ('.') or the parent directory ('..'). If the item is a directory, it adds its name to the directories array.

Finally, the method returns the directories array, which contains the names of all subdirectories in the specified directory.

To use this method, you can simply call it with the path to the directory you want to search, like this:

all_directories = get_all_directories('/path/to/directory')

This will return an array of directory names, which you can then use for further processing.