MxLDevs
MxLDevs

Reputation: 19506

Filename matching, extension not important

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

Answers (2)

Ismael
Ismael

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

user1549550
user1549550

Reputation:

Use Dir::glob.

Dir::glob("#{dir}/#{name}.*")

Upvotes: 3

Related Questions