Getting a list of folders in a directory

66,357

Solution 1

Jordan is close, but Dir.entries doesn't return the full path that File.directory? expects. Try this:

 Dir.entries('/your_dir').select {|entry| File.directory? File.join('/your_dir',entry) and !(entry =='.' || entry == '..') }

Solution 2

I've found this more useful and easy to use:

Dir.chdir('/destination_directory')
Dir.glob('*').select {|f| File.directory? f}

it gets all folders in the current directory, excluded . and ...

To recurse folders simply use ** in place of *.

The Dir.glob line can also be passed to Dir.chdir as a block:

Dir.chdir('/destination directory') do
  Dir.glob('*').select { |f| File.directory? f }
end

Solution 3

In my opinion Pathname is much better suited for filenames than plain strings.

require "pathname"
Pathname.new(directory_name).children.select { |c| c.directory? }

This gives you an array of all directories in that directory as Pathname objects.

If you want to have strings

Pathname.new(directory_name).children.select { |c| c.directory? }.collect { |p| p.to_s }

If directory_name was absolute, these strings are absolute too.

Solution 4

Recursively find all folders under a certain directory:

Dir.glob 'certain_directory/**/*/'

Non-recursively version:

Dir.glob 'certain_directory/*/'

Note: Dir.[] works like Dir.glob.

Solution 5

With this one, you can get the array of a full path to your directories, subdirectories, subsubdirectories in a recursive way. I used that code to eager load these files inside config/application file.

Dir.glob("path/to/your/dir/**/*").select { |entry| File.directory? entry }

In addition we don't need deal with the boring . and .. anymore. The accepted answer needed to deal with them.

Share:
66,357
0xC0DEFACE
Author by

0xC0DEFACE

Updated on July 08, 2022

Comments

  • 0xC0DEFACE
    0xC0DEFACE almost 2 years

    How do I get a list of the folders that exist in a certain directory with ruby?

    Dir.entries() looks close but I don't know how to limit to folders only.