views:

214

answers:

5

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.

A: 

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

matekm
A: 

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
+1  A: 

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 == '..') }
ScottD
Note that this will get you *all* directories, including hidden ones as well as `'.'` (current directory) and `'..'` (parent of current directory). In most cases, you want to remove at least those two.
Telemachus
Good point. Corrected for . and ..
ScottD
A: 
directory = 'Folder'
puts Dir.entries(directory).select { |file| File.directory? File.join(directory, file)}
Markus
+3  A: 

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.

johannes