gpt4 book ai didi

ruby-on-rails - 从文件列表中,为 dynatree 动态创建哈希数组

转载 作者:太空宇宙 更新时间:2023-11-03 18:16:19 24 4
gpt4 key购买 nike

我有一个按数组排序的文件列表,例如:

arr = ["./a.txt", "./b.txt", "./bar/z.php", "./foo/hello/y.php", "./foo/x.php"]

如何从中创建动态树对象?它的 dynatree 对象应该是这样的:

[{"name"=>".", "title" => ".", "isDir" => true, "children" => 
[{"name"=>"a.txt", "title" => "a.txt"},
{"name"=>"b.txt", "title" => "b.txt"},
{"name" => "bar", "title"=>"bar", "isDir"=>true, "children" =>
[{"name" => "z.php", "title" => "z.php"},
{"name" => "foo", "title" => "foo", "isDir" => true, "children" =>
[{"name" => "x.php", "title" => "x.php"},
{ "name" => "hello", "title" => "hello", "children" =>
[{"name" => "y.php", "title"=>"y.php"}
]
}
]
}
]
}
]
}]

PS:这个问题可能看起来很懒,但我现在已经花了 20 多个小时来解决这个问题。因此,我们将不胜感激任何帮助。谢谢。

最佳答案

我喜欢选择更加模块化的方法。首先,我将构建一个方法 make_tree 将文件路径列表转换为嵌套哈希:

require 'pathname'

def insert_node(tree, parts)
head, *tail = parts
tree[head] ||= {}
insert_node tree[head], tail unless tail.empty?
tree
end

def make_tree(paths)
paths.reduce({}) do |tree, file|
insert_node tree, Pathname(file).each_filename.to_a
end
end

这是一个示例 - 此输出稍后将仅用作中间结果:

paths = ["./a.txt", "./b.txt", "./bar/z.php", "./foo/hello/y.php", "./foo/x.php"]
tree = make_tree(paths)
#=> {"."=>
# {"a.txt"=>{},
# "b.txt"=>{},
# "bar"=>{"z.php"=>{}},
# "foo"=>{"hello"=>{"y.php"=>{}}, "x.php"=>{}}}}

然后,我们可以编写一个函数将这个嵌套哈希转换为“dynatree”表示:

def make_dynatree(tree)
tree.map do |node, subtree|
if subtree.empty?
{"name" => node, "title" => node}
else
{"name" => node, "title" => node, "isDir" => true, "children" => make_dynatree(subtree)}
end
end
end

最后:

dynatree = make_dynatree(tree)
#=> [{"name"=>".", "title"=>".", "isDir"=>true, "children"=>
# [{"name"=>"a.txt", "title"=>"a.txt"},
# {"name"=>"b.txt", "title"=>"b.txt"},
# {"name"=>"bar", "title"=>"bar", "isDir"=>true, "children"=>[
# {"name"=>"z.php", "title"=>"z.php"}]},
# {"name"=>"foo", "title"=>"foo", "isDir"=>true, "children"=>[
# {"name"=>"hello", "title"=>"hello", "isDir"=>true, "children"=>[
# {"name"=>"y.php", "title"=>"y.php"}]},
# {"name"=>"x.php", "title"=>"x.php"}]}]}]

关于ruby-on-rails - 从文件列表中,为 dynatree 动态创建哈希数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25681318/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com