I am attempting to find a file by its name within a directory. I am not sure what the best approach to this problem is. The file could be nested in other directories within the root directory.
Asked
Active
Viewed 1,470 times
3 Answers
4
You can use Dir.glob, for example:
Dir.glob(File.join("**","*.rb"))
It will recursively look for "*.rb" files in your current directory.

lhdv
- 146
- 1
- 6
3
this should work for you:
require 'find'
file_name = /log\Z/
path = './'
found_files = Find.find(path).inject([]) do |files, entry|
File.file?(entry) && File.basename(entry) =~ file_name ?
files << entry : files
end
p found_files
#=> ["./Maildir/dovecot.index.log", "./pgadmin.log"]
change file_name
and path
to your needs.
-
I am giving lhoffman the accept because his is shorter, but yours works as well – richsoni Nov 29 '12 at 16:24
-
Shorter shouldn't be the criteria, speed, memory usage and maintainability are more important than size. – the Tin Man May 27 '16 at 19:43