4

Ruby を使用してマテリアライズド パスからツリー構造を構築するのに問題があります。

(couchdb から) 並べ替えられた結果セットがあるとします。

[
  { :key => [], :value => "Home" },
  { :key => ["about"], :value => "About" },
  { :key => ["services"], :value => "Services" },
  { :key => ["services", "plans"], :value => "Plans" },
  { :key => ["services", "training"], :value => "Training" },
  { :key => ["services", "training", "python"], :value => "Python" },
  { :key => ["services", "training", "ruby"], :value => "Ruby" }
]

ルビーのツリーとしてこれが必要なだけです。次のハッシュで十分です:

{ :title => "Home", :path => [], :children => [
  { :title => "About", :path => ["about"] }, 
  { :title => "Services", :path => ["services"], :children => [
    { :title => "Plans", :path => ["services", "plans"] }
  ]}
]}

誰でも私を助けることができますか?

4

1 に答える 1

4

単純なヘルパー クラスと少しの再帰だけで十分です。

class Tree
  attr_reader :root

  def initialize
    @root = { :title => 'Home', :path => [ ], :children => [ ] }
  end

  def add(p)
    r_add(@root, p[:key].dup, p[:value])
    self
  end

private

  def r_add(h, path, value)
    if(path.empty?)
      h[:title] = value 
      return
    end

    p = path.shift
    c = h[:children].find { |c| c[:path].last == p } 
    if(!c)
      c = { :title => nil, :path => h[:path].dup.push(p), :children => [ ] }
      h[:children].push(c)
    end
    r_add(c, path, value)
  end

end

その後:

t = a.inject(Tree.new) { |t, h| t.add(h) }
h = t.root

でこれを与えるでしょうh

{:title =>"Home", :path=>[], :children=>[
  {:title=>"About", :path=>["about"], :children=>[]},
  {:title=>"Services", :path=>["services"], :children=>[
    {:title=>"Plans", :path=>["services", "plans"], :children=>[]},
    {:title=>"Training", :path=>["services", "training"], :children=>[
      {:title=>"Python", :path=>["services", "training", "python"], :children=>[]}, 
      {:title=>"Ruby", :path=>["services", "training", "ruby"], :children=>[]}
    ]}
  ]}
]}

:childrenそれらが重要な場合は、空のものを整理できます。

于 2011-10-20T04:31:48.627 に答える