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.
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.
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 == '..') }
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.
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.
You can use File.directory? from the FileTest module to find out if a file is a directory. Combining this with Dir.entries makes for a nice one(ish)-liner:
directory = 'some_dir'
Dir.entries(directory).select { |file| File.directory?(File.join(directory, file)) }
Edit: Updated per ScottD's correction.
directory = 'Folder'
puts Dir.entries(directory).select { |file| File.directory? File.join(directory, file)}
Only folders ('.' and '..' are excluded):
Dir.glob(File.join(path, "*", File::SEPARATOR))
Folders and files:
Dir.glob(File.join(path, "*"))
I think you can test each file to see if it is a directory with FileTest.directory? (file_name). See the documentation for FileTest for more info.