我有一个路径数组,array = [ 'A.TXT', 'B / A.TXT', 'A / A.TXT', 'A / Z / A.TXT' ]
我需要创建一个树结构(对于jTree插件),但它必须先按文件夹排序(按字母顺序排列)然后按叶子排序(按字母顺序排列)。
带有上述示例的有序树结构如下所示:
编辑:我正在寻找构建一个HTML有序列表和列表项的树,其中每个节点都是LI,如果它是一个文件夹,它有另一个UL作为兄弟。这是jTree插件作为输入采用的格式之一。以上示例的结构:
<ul>
<li class="folder">a</li>
<ul>
<li class="folder">z</li>
<ul>
<li class="leaf">a.txt</li>
</ul>
</ul>
<li class="folder">b</li>
<ul>
<li class="leaf">a.txt</li>
</ul>
<li class="leaf">a.txt</li>
</ul>
这将构建树结构作为哈希树:
array = ["home", "about", "about/history", "about/company", "about/history/part1", "about/history/part2"]
auto_hash = Hash.new{ |h,k| h[k] = Hash.new &h.default_proc }
array.each{ |path|
sub = auto_hash
path.split( "/" ).each{ |dir| sub[dir]; sub = sub[dir] }
}
答案 0 :(得分:2)
require 'rubygems'
require 'builder'
paths = ["home", "about", "about/history", "about/company", "about/history/part1", "about/history/part2"]
auto_hash = Hash.new{ |h,k| h[k] = Hash.new &h.default_proc }
paths.each do |path|
sub = auto_hash
path.split( "/" ).each{ |dir| sub[dir]; sub = sub[dir] }
end
def build_branch(branch, xml)
directories = branch.keys.reject{|k| branch[k].empty? }.sort
leaves = branch.keys.select{|k| branch[k].empty? }.sort
directories.each do |directory|
xml.li(directory, :class => 'folder')
xml.ul do
build_branch(branch[directory], xml)
end
end
leaves.each do |leaf|
xml.li(leaf, :class => 'leaf')
end
end
xml = Builder::XmlMarkup.new(:indent => 2)
xml.ul do
build_branch(auto_hash, xml)
end
puts xml.target!