Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have an of strings which are file names files, and an array of allowed file types or suffixes allowed_types. I want to filter out files which don't end with an allowed suffix.

This does the trick, but I'm wondering if anyone can suggest a neater solution? Such as a way keep with ruby's usual streamlined style without using flag variables.

valid_files = Dir.entries(path).select do |f| 
  valid = false
  allowed_types.each { |suffix| next valid = true if f.end_with? suffix }
  next valid
end
share|improve this question

migrated from stackoverflow.com Jul 23 '12 at 20:32

This question came from our site for professional and enthusiast programmers.

1 Answer 1

up vote 4 down vote accepted

How about this?

valid_files = Dir.entries(path).select do |f| 
  allowed_types.any? {|suffix| f.end_with? suffix}
end
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.