Directory Traversal in Ruby
ruby
Solution
The problem is that each time you recurse, the path you pass to `File.directory?` is no is just the entity (file or directory) name; all context is lost. So say you go into `one/two/three/` to check if `one/two/three/file.txt` is a directory, `File.directory?` just gets `"file.txt"` as the path instead of the whole thing, from the perspective of the top-level directory. You have to maintain the relative path each time you recurse. This seems to work fine:
def walk(start)
Dir.foreach(start) do |x|
path = File.join(start, x)
if x == "." or x == ".."
next
elsif File.directory?(path)
puts path + "/" # remove this line if you want; just prints directories
walk(path)
else
puts x
end
end
end
Problem
I have been trying to implement a directory traversal in Ruby for part of a bigger program using the simple recursive approach. However I have found that Dir.foreach does not include the directories inside of it. How can I get them listed? Code: ``` def walk(start) Dir.foreach(start) do |x| if x == "." or x == ".." next elsif File.directory?(x) walk(x) else puts x end end end ```