루비

2010-03-06 3 views
1

에 의해 첫번째 폴더 트리 구조를 정렬 I는 경로 배열 = 'a.txt이'의 배열 'B/a.txt이' 'A/a.txt이' 을 '이있다 /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] } 
} 
+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! 
+0

머니와 문제가 있습니다. 감사 :) –