2010-03-06 49 views
1

我的路徑,陣列= [ 'A.TXT' 的陣列, 'B/A.TXT', 'A/A.TXT', 「一/z/a.txt」 ]通過文件夾分類樹結構的第一Ruby中

我需要創建一個樹形結構(JTree的插件),但它必須通過文件夾第一(按字母順序),然​​後葉(按字母順序太)排序。

排序的樹結構,將上面的例子應該是這樣的:

  • 一個
    • Ž
      • 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] } 
} 
+0

構建樹結構容易(很多例子在線),排序是部分IM與 – 2010-03-06 00:39:08

回答

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! 
+0

有問題錢!謝謝 :) – 2010-03-06 03:08:16

相關問題