【问题标题】:Sorting a tree structure by folders first in Ruby在Ruby中首先按文件夹对树结构进行排序
【发布时间】:2010-03-06 00:30:28
【问题描述】:

我有一个路径数组,array = [ 'a.txt', 'b/a.txt', 'a/a.txt', 'a/z/a.txt' ]

我需要创建一个树结构(用于 jTree 插件),但它必须先按文件夹排序(按字母顺序),然​​后再按叶子(也按字母顺序)。

上面示例的排序树结构如下所示:

  • 一个
    • z
      • a.txt
    • a.txt
  • 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] }
}

【问题讨论】:

  • 构建树形结构很容易(网上有很多例子),排序是我遇到问题的部分

标签: ruby sorting tree structure


【解决方案1】:
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!

【讨论】:

    猜你喜欢
    • 2013-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-11
    • 2021-08-01
    • 1970-01-01
    • 2018-06-13
    相关资源
    最近更新 更多