Using Dir.glob to grab only Directories

M

Mario Gr

Hi,

I was wondering if there were a way to use Dir.glob to grab only
directories. After searching google for a bit I found ways to pull only
file listings, but couldn't find one for just directories.

Currently, I'm using FileTest.directory?(dir) before running any
operations to test for a directory.
 
A

Andrea Fazzi

Mario said:
Hi,

I was wondering if there were a way to use Dir.glob to grab only
directories. After searching google for a bit I found ways to pull only
file listings, but couldn't find one for just directories.

Currently, I'm using FileTest.directory?(dir) before running any
operations to test for a directory.

# Non-recursive
Dir.glob('*').select { |fn| File.directory?(fn) }

# Recursive
Dir.glob('**/*').select { |fn| File.directory?(fn) }
 
R

Robert Klemme

# Non-recursive
Dir.glob('*').select { |fn| File.directory?(fn) }

# Recursive
Dir.glob('**/*').select { |fn| File.directory?(fn) }

For deep hierarchies it may be more efficient to use Find because you
avoid creating a large Array with lots of file names most of which you
do not want.

# untested
require 'find'
DOTS = %w{. ..}

Find.find base_dir do |f|
next if DOTS.include?(File.basename(f)) || !test(?d, f)
puts "A dir which is not . or ..: #{f}"
end

Kind regards

robert
 
I

Intransition

Hi,

I was wondering if there were a way to use Dir.glob to grab only
directories. =A0After searching google for a bit I found ways to pull onl= y
file listings, but couldn't find one for just directories.

Currently, I'm using FileTest.directory?(dir) before running any
operations to test for a directory.

Trailing '/':

Dir.glob('*/').select { |fn| File.directory?(fn) }
Dir.glob('**/*/').select { |fn| File.directory?(fn) }
 
I

Intransition

Trailing '/':

Dir.glob('*/').select { |fn| File.directory?(fn) }
Dir.glob('**/*/').select { |fn| File.directory?(fn) }

Sorry, I meant:

Dir.glob('*/')
Dir.glob('**/*/')

The trailing '/' makes the select unnecessary.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,021
Latest member
AkilahJaim

Latest Threads

Top