views:

99

answers:

4

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

A: 

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)
johannes
+3  A: 
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).

sepp2k
thanks, was missing that trailing slash.
viatropos
use `Dir.glob("**/")` unless you also want symlinks
johannes
A: 

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['**/*']
MBO
Note that he said "also include files", not "only files" so you don't need to remove the directories.
sepp2k
@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
A: 

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?

Ramesh