atkayla
atkayla

Reputation: 8849

How do I do a Dir.glob but exclude directories?

If I wanted to get all of the CSS and JavaScript files

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

gives me stuff I don't want if there's a folder named stupidfolder.js. I would just change the name of the folder, but I can't.

Upvotes: 10

Views: 5778

Answers (3)

knut
knut

Reputation: 27855

It may be an exaggeration for your problem, but rake defines a class FileList. You could replace Dir.glob with this class:

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

Upvotes: 5

Richard Hamilton
Richard Hamilton

Reputation: 26434

You can do it with Dir.entries

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

Upvotes: 4

user229044
user229044

Reputation: 239291

You can't do that with Dir.glob. You have to reject those entries explicitly.

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

Upvotes: 13

Related Questions