Zero
Zero

Reputation: 584

Ruby / Rails find file with name like

i try to find all files in a directory which has a name like "test".

So in my directory (/test/files/example) i got following files:

How can i get all the files with the File Class in Ruby? I do this but i think you see the struggle

10.times do |count|
  file_path = "/test/files/example/test_#{count}.wav"
  if File.exist?(file_path)
    @files[count] = file_path
    next
  end
  break
end

Upvotes: 6

Views: 6115

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230306

Globbing is the way to go. This will return an array of filenames matching your pattern.

Dir["/test/files/example/test_*.wav"]

The return value is an array of strings, which you may sort however you like.

Upvotes: 13

Related Questions