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

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


I know this is 4 years late but for anybody else that might run across this question you can exclude from Dir the same way you would exclude from Bash wildcards:

Dir["lib/{[!errors/]**/*,*}.rb"]

Which will exclude any folder that starts with "errors" you could even omit the / and turn it into a wildcard of sorts too if you want.


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 filenameend

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


There's FileList from the Rake gem (which is almost always installed by default, and is included in the standard library in Ruby 1.9):

files = FileList['**/*.h'].exclude('skip_me')

FileList has lots of functionality for working with globs efficiently.

You can find the documentation here: http://rake.rubyforge.org/classes/Rake/FileList.html