Ruby 创建递归目录树 [英] Ruby Create Recursive Directory Tree
本文介绍了Ruby 创建递归目录树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要递归遍历一个目录并创建一个树以与 jsTree 控件一起使用.该控件接受 JSON 格式像这样.我需要一些 ruby 魔法才能干净、快速地完成这件事.
I need to recursively traverse a directory and create a tree to be used with the jsTree control. The control accepts a JSON format like so. I need some ruby magic to make this happen cleanly and quickly.
感谢任何帮助.
推荐答案
你可能想要这样的东西(未经测试):
You probably want something like this (untested):
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.
Recursively walk down the tree, building up a hash. Turn it into json with your favourite serialisation library.
这篇关于Ruby 创建递归目录树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文