在 Ruby 中首先按文件夹对树结构进行排序
我有一个路径数组, array = [ 'a.txt', 'b/a.txt', 'a/a.txt', 'a/z/a.txt' ]
我需要创建一个树结构(用于 jTree 插件),但它必须首先按文件夹排序(按字母顺序),然后按叶子排序(也按字母顺序)。
上述示例的排序树结构如下所示
- :
- z
- a.txt
- a.txt
- z
- b
- a.txt
- a.txt
编辑:我希望构建一个 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] }
}
I have an array of paths, array = [
'a.txt',
'b/a.txt',
'a/a.txt',
'a/z/a.txt'
]
I need to create a tree structure (for the jTree plugin), but it has to be sorted by folders first (alphabetically) and then leafs (alphabetically too).
A sorted tree structure with the above example would look like this:
- a
- z
- a.txt
- a.txt
- z
- b
- a.txt
- a.txt
EDIT: Im looking to build a Tree of HTML ordered lists and list items, where each node is a LI and if its a folder it has another UL as a sibling. This is one of the formats the jTree plugin takes as input. Structure for above example:
<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>
This will build the tree structure as a hash tree:
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] }
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)