110

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

How about including files?

1
  • 3
    Fastest, most optimized and one-liner can be at odds with readable/maintainable. And, you could find this out using a benchmark and quick testing. May 27, 2016 at 19:34

9 Answers 9

200
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

6
  • 10
    use Dir.glob("**/") unless you also want symlinks
    – johannes
    Mar 3, 2010 at 15:37
  • 6
    What about hidden files and directories? Aug 30, 2012 at 10:20
  • 6
    To include dotfiles in the match results, use the File::FNM_DOTMATCH flag.
    – x-yuri
    Jul 1, 2014 at 18:06
  • 2
    Thanks @x-yuri! The flag btw is specified like this: Dir.glob("**/*", File::FNM_DOTMATCH)
    – vlz
    Nov 5, 2014 at 11:50
  • 2
    Here's the documentation: ruby-doc.org/core-2.2.0/Dir.html#method-c-glob Jan 30, 2015 at 3:03
54

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) }
2
35

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['**/*']
2
  • Note that he said "also include files", not "only files" so you don't need to remove the directories.
    – sepp2k
    Mar 3, 2010 at 11:43
  • 3
    @sepp2k Yes, I missed this part when I was playing with irb. But I leave this here in case someone might search for something similar :-)
    – MBO
    Mar 3, 2010 at 11:45
8

As noted in other answers here, you can use Dir.glob. Keep in mind that folders can have lots of strange characters in them, and glob arguments are patterns, so some characters have special meanings. As such, it's unsafe to do something like the following:

Dir.glob("#{folder}/**/*")

Instead do:

Dir.chdir(folder) { Dir.glob("**/*").map {|path| File.expand_path(path) } }
7

Fast one liner

Only directories

`find -type d`.split("\n")

Directories and normal files

`find -type d -or -type f`.split("\n")`

Pure beautiful ruby

require "pathname"

def rec_path(path, file= false)
  puts path
  path.children.collect do |child|
    if file and child.file?
      child
    elsif child.directory?
      rec_path(child, file) + [child]
    end
  end.select { |x| x }.flatten(1)
end

# only directories
rec_path(Pathname.new(dir), false)
# directories and normal files
rec_path(Pathname.new(dir), true)
2
  • 1
    False: Dir.glob("#{DIRECTORY}/**/*/").map {|directory| Pathname.new(directory) } Feb 12, 2013 at 20:14
  • Can anyone explain the end.select {}.flatten() part? I like the function overall. It looks like that will create an array of arrays? Would it be possible to do the elseif part with: rec_path(child, file) << child.to_s so that you could assign it to an array and get an array of strings? Thanks!
    – MCP
    Jun 3, 2013 at 5:30
2

In PHP or other languages to get the content of a directory and all its subdirectories, you have to write some lines of code, but in Ruby it takes 2 lines:

require 'find'
Find.find('./') do |f| p f end

this will print the content of the current directory and all its subdirectories.

Or shorter, You can use the ’**’ notation :

p Dir['**/*.*']

How many lines will you write in PHP or in Java to get the same result?

2
0

Here's an example that combines dynamic discovery of a Rails project directory with Dir.glob:

dir = Dir.glob(Rails.root.join('app', 'assets', 'stylesheets', '*'))
1
  • I tried this>> config.assets.paths << Rails.root.join("app", "assets", "*"), but still couldn't see the sub-folders and files inside the assets folder by Rails.application.config.assets.paths Mar 14, 2016 at 8:52
-1
Dir.open(Dir.pwd).map { |h| (File.file?(h) ? "#{h} - file" : "#{h} - folder") if h[0] != '.' }

dots return nil, use compact

1
  • 1
    This is not too elegant, and would need to be on a few more lines to be so
    – onebree
    Aug 13, 2015 at 12:39
-3

Although not a one line solution, I think this is the best way to do it using ruby calls.

First delete all the files recursively
Second delete all the empty directories

Dir.glob("./logs/**/*").each { |file| File.delete(file) if File.file? file }
Dir.glob("./logs/**/*/").each { |directory| Dir.delete(directory) }
3
  • 4
    He/she doesn't want to delete files/directories. Feb 6, 2015 at 21:26
  • How to do this for both files+directory in a single line? Mar 14, 2016 at 8:50
  • 1
    Wow, this is a really bad answer: a.) it doesn't answer the original question and b.) it is destructive when c&p by an unexperienced ...
    – lumpidu
    Jun 7, 2021 at 10:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.