最佳答案
你可能想要这样的东西(未经测试):
def directory_hash(path, name=nil)
data = {:data => (name || path)}
data[:children] = children = []
Dir.foreach(path) do |entry|
next if (entry == '..' || entry == '.')
full_path = File.join(path, entry)
if File.directory?(full_path)
children << directory_hash(full_path, entry)
else
children << entry
end
end
return data
end
递归地沿着树向下走,构建一个散列。使用您最喜欢的序列化库将其转换为 json。
关于ruby-on-rails - Ruby 创建递归目录树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5520501/