Reputation: 19506
I want to write a method that does this
def search_for_filenames(dir, name)
# goes to the directory and returns a list of files that match
# the given name, regardless of extension
end
So for example if the name was test
, and my directory contained the following
test.png
test.txt
something_else.dat
The method will return an array containing the first two filenames
How can I write this method?
Upvotes: 1
Views: 782
Reputation: 16720
Tough it would be faster then Dir::glob
but it actually can take more time to run sometimes. Anyway, here is what I have done. But use Dir::glob
.
def search_for_filenames(dir, name)
result_files = []
Dir.new(dir).each do |file|
if /^#{name}\.\w+$/.match file
result_files << file
return result_files if result_files.size == 2
end
end
result_files
end
Upvotes: 0