user137369
user137369

Reputation: 5706

Match multiple conditions in Array#reject

I have a directory. I want to select all files (but no directories) that don’t have an .mp3 extension. This works:

Dir.glob("#{dir}/**/*").reject { |f| File.directory?(f) }.reject { |f| File.extname(f) == '.mp3' }

But if possible, I’d like to do it in a single swoop. I’ve tried the following:

Dir.glob("#{dir}/**/*").reject { |f| File.file?(f) && File.extname(f) == '.mp3' }

But it doesn’t work. It does ignore non-.mp3 files, but it still include directories.

Upvotes: 2

Views: 1569

Answers (1)

spickermann
spickermann

Reputation: 106882

You want to reject all files that are a directory or have the mp4 extension. Just write it like this:

Dir.glob("#{dir}/**/*")
   .reject { |f| File.directory?(f) || File.extname(f) == '.mp3' }

Or you might want to negate the condition and use select instead. Select everything that is a file and does not have the mp3 extension:

Dir.glob("#{dir}/**/*")
   .select { |f| File.file?(f) && File.extname(f) != '.mp3' }

Upvotes: 2

Related Questions