我一直在尝试使用简单的递归方法在Ruby中实现一个更大程序的部分目录遍历.但是我发现Dir.foreach不包含其中的目录.我怎样才能列出它们?
码:
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
Run Code Online (Sandbox Code Playgroud)
Jor*_*eña 13
问题是,每次递归时,传递给的路径File.directory?都是"否"只是实体(文件或目录)名称; 所有背景都丢失了.所以说你从顶层目录的角度来看one/two/three/是否one/two/three/file.txt是一个目录,File.directory?只是"file.txt"作为路径而不是整个路径.每次递归时都必须保持相对路径.这似乎工作正常:
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
Run Code Online (Sandbox Code Playgroud)
the*_*Man 11
对于递归,您应该使用Find:
从文档:
Find模块支持自上而下遍历一组文件路径.
例如,要总计主目录下所有文件的大小,忽略"点"目录中的任何内容(例如$ HOME/.ssh):
require 'find'
total_size = 0
Find.find(ENV["HOME"]) do |path|
if FileTest.directory?(path)
if File.basename(path)[0] == .
Find.prune # Don't look any further into this directory.
else
next
end
else
total_size += FileTest.size(path)
end
end