jarjar jarjar - 3 months ago 130
Ruby Question

Is there a way to glob a directory in Ruby but exclude certain directories?

I want to glob a directory to post-process header files. Yet I want to exclude some directories in the project. Right now the default way is...

Dir["**/*.h"].each { |header|
puts header

Seems inefficient to check each header entry manually if it's in an excluded directory.


Don't use globbing, instead use Find. Find is designed to give you access to the directories and files as they're encountered, and you programmatically decide when to bail out of a directory and go to the next. See the example on the doc page.

If you want to continue using globbing this will give you a starting place. You can put multiple tests in reject or'd together:

Dir['**/*.h'].reject{ |f| f['/path/to/skip'] || f[%r{^/another/path/to/skip}] }.each do |filename|
  puts filename

You can use either fixed-strings or regex in the tests.