从物化路径构建树

从物化路径构建树

本文介绍了从物化路径构建树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用ruby从物化路径构建树结构时遇到麻烦。

I have a trouble building a tree structure from materialized path using ruby.

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

Assuming I have a sorted result set (from 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" }
]

我只需要将其作为红宝石中的一棵树,以下哈希足够好:

I just need this as a tree in ruby,the following hash is good enough:

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

有人可以帮我吗?

推荐答案

一个简单的帮助器类和一点递归就是您所需要的:

A simple helper class and a bit of recursion is all you need:

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

您可以整理空的:儿童如果他们很重要。

You can sort out the empty :children if they matter.

这篇关于从物化路径构建树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 15:03