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.
I think You can test each file if it is directory with FileTest.directory? (file_name). See documentation of FileTest for more info: http://ruby-doc.org/core/classes/FileTest.html
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.
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 == '..') }
directory = 'Folder'
puts Dir.entries(directory).select { |file| File.directory? File.join(directory, file)}
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 directorys 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.