I have an array of extensions and an array of file names:
exts = ['.zip', '.tgz', '.sql']
files = ['file1.txt', 'file2.doc', 'file2.tgz', 'file3.sql', 'file6.foo', 'file4.zip']
I want to filter the file names by one or more matching extensions. In this case, the result would be:
["file1.zip", "file2.tgz", "file3.sql", "file4.zip"]
I know I can do this with a nested loop:
exts.each_with_object([]) do |ext, arr|
files.each do |file|
arr << entry if file.include?(ext)
end
end
This feels ugly to me. With select, I can avoid the feeling of nested loops:
files.select { |file| exts.each { |ext| file.include?(ext) } }
This works and feels better. Is there still a more elegant way that I'm missing?
filescome from? If you are filtering files in a directory,Dir.globcould be a better approach.