Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Built in way to list directories in a directory in ruby

Is there a cleaner built-in way to do this?

ree> Pathname.new('/path/to').children.select{|e| e.directory?}.map{|d| d.basename.to_s}
 => ["test1", "test2"]

Ideally I would like to avoid the directory? call

like image 561
Sam Saffron Avatar asked Jan 06 '10 06:01

Sam Saffron


People also ask

How do I list all subfolders in a directory?

Substitute dir /A:D. /B /S > FolderList. txt to produce a list of all folders and all subfolders of the directory. WARNING: This can take a while if you have a large directory.

How do I get a list of directories in R?

The list. dirs() method in R language is used to retrieve a list of directories present within the path specified. The output returned is in the form of a character vector containing the names of the files contained in the specified directory path, or returns null if no directories were returned.


2 Answers

Starting from Chandra's answer, depending on whether you need or not the full path, you can use

Dir['app/*/']
# => ["app/controllers/", "app/helpers/", "app/metal/", "app/models/", "app/sweepers/", "app/views/"

Dir['app/*/'].map { |a| File.basename(a) }
# => ["controllers", "helpers", "metal", "models", "sweepers", "views"]

If you use Ruby >= 1.8.7, Chandra's answer can also be rewritten as

Pathname.glob('app/*/').map(&:basename)
# you can skip .to_s unless you don't need to work with strings
# remember you can always use a pathname as string for the most part of Ruby functions
# or interpolate the value
like image 198
Simone Carletti Avatar answered Nov 03 '22 08:11

Simone Carletti


Pathname.glob("/path/to/*/").map { |i| i.basename.to_s }
like image 45
Chandra Patni Avatar answered Nov 03 '22 09:11

Chandra Patni