I want to write a program that get from user a path and then go to that directory and all of subdirectories recurcively and collect all txt files. but "." and ".." bother me when I am iterating directories recurcively. please help me to eradicating this problem. th开发者_开发百科is is my code :
def detect_files(path)
Dir.foreach(path) do |i|
if (i != "." or i !="..")
if (File.directory?(i))
detect_files(i)
end
if (i.reverse.start_with?("txt."))
@files[i]=[]
end
end
end
end
The condition should be :
if (i != "." and i != "..")
- If
i="."
theni != "."
will be false making the condition false, and"."
will not be processed - If
i=".."
theni != "."
will be true buti != ".."
will be false, making the condition false and".."
will not be processed. - If
i
has any other values, then both side ofand
will be true and the body ofif
will be executed.
Dir.foreach(path) do |i|
next if %w(. ..).include?(i)
# rest of your code
end
Your current version has a wrong condition for the if
: you want (i != '.' AND i != '..')
.
all_txt_files = Dir['**/*.txt']
You could try just doing something like this
def detect_files(path)
p1 = File.join(path, '**', '*.txt')
@files = Dir[p1]
end
Try like this:
Dir.foreach('/path/to/dir') do |item|
next if item == '.' or item == '..'
# do work on real items
end
OR
Dir.glob('/path/to/dir/*.rb') do |rb_file|
# do work on files ending in .rb in the desired directory
end
精彩评论