Reputation: 59
I have successfully build a file finder with Dir.glob but now am wanting to know if the file is not found as well - dealing with 1000's of files so I need to know if one is not found.
The code I have is this:
# code above gets a file name from a list of in a file then I search the computer for the file:
Dir.glob("#{folder}/**/#{search_file_name}") do |f|
if File.exists?(f)
puts "the file name #{f} is found"
puts "now I am working on #{f}"
else
puts "the file #{f} cannot be found"
end
#the rest of the code moves the file to a another directory if found.
This works well for files that exists. But if the file does not exists I do not get a message in the terminal to that effect. I am missing something obvious. Perhaps my Dir.glob only holds the files it finds so that |f| never passes a file to the if statement if it does not exists.
Upvotes: 1
Views: 231
Reputation: 1873
You can't iterate through an empty Array. There is no need to set a conditional with File.exist?. Dir.glob will return [] if the file can not be found.
def find_files(folder, search_file_name)
file = Dir.glob("#{folder}/**/#{search_file_name}")
puts "the file #{search_file_name} can't be found" if file.empty?
file.each do |f|
puts "the file name #{f} is found"
puts "now I am working on #{f}"
end
end
Upvotes: 4