Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 从物化路径构建树_Ruby_Tree_Couchdb_Materialized Path Pattern - Fatal编程技术网

Ruby 从物化路径构建树

Ruby 从物化路径构建树,ruby,tree,couchdb,materialized-path-pattern,Ruby,Tree,Couchdb,Materialized Path Pattern,我很难使用ruby从物化路径构建树结构 假设我有一个排序结果集(来自couchdb): 我只需要将其作为ruby中的树,下面的哈希就足够了: { :title => "Home", :path => [], :children => [ { :title => "About", :path => ["about"] }, { :title => "Services", :path => ["services"], :children =>

我很难使用ruby从物化路径构建树结构

假设我有一个排序结果集(来自couchdb):

我只需要将其作为ruby中的树,下面的哈希就足够了:

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

有人能帮我吗?

您只需要一个简单的助手类和一点递归:

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=>[]}
    ]}
  ]}
]}
你可以把空的
:子项
分类,如果它们很重要的话

{: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=>[]}
    ]}
  ]}
]}