How do I make Dir.glob but exclude directories?

If I wanted to get all the CSS and JavaScript files

Dir.glob("dir/**/*.{css,js}) 

gives me stuff that I don't want if there is a folder called stupidfolder.js . I would just change the name of the folder, but I cannot.

+7
ruby
source share
3 answers

You cannot do this with Dir.glob . You must explicitly reject these entries.

 only_files = Dir.glob('*').reject do |path| File.directory?(path) end 
+10
source share

You can do it with Dir.entries

 Dir.entries('../directoryname').reject { |f| File.directory?(f) } 
+4
source share

This may be an exaggeration for your problem, but rake defines the FileList class. You can replace Dir.glob with this class:

 require 'rake' filelist = FileList.new("dir/**/*.{css,js}") filelist.exclude('**/stupidfolder.js') filelist.each do |file| #... end 
+4
source share

All Articles