Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One-liner to recursively list directories in Ruby?

What is the fastest, most optimized, one-liner way to get an array of the directories (excluding files) in Ruby?

How about including files?

like image 693
Lance Avatar asked Mar 03 '10 11:03

Lance


3 Answers

Dir.glob("**/*/") # for directories
Dir.glob("**/*") # for all files

Instead of Dir.glob(foo) you can also write Dir[foo] (however Dir.glob can also take a block, in which case it will yield each path instead of creating an array).

Ruby Glob Docs

like image 124
sepp2k Avatar answered Nov 18 '22 10:11

sepp2k


I believe none of the solutions here deal with hidden directories (e.g. '.test'):

require 'find'
Find.find('.') { |e| puts e if File.directory?(e) }
like image 54
FelipeC Avatar answered Nov 18 '22 08:11

FelipeC


For list of directories try

Dir['**/']

List of files is harder, because in Unix directory is also a file, so you need to test for type or remove entries from returned list which is parent of other entries.

Dir['**/*'].reject {|fn| File.directory?(fn) }

And for list of all files and directories simply

Dir['**/*']
like image 34
MBO Avatar answered Nov 18 '22 10:11

MBO