从物化路径构建树

编程入门 行业动态 更新时间:2024-10-22 08:43:28
本文介绍了从物化路径构建树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在使用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.

更多推荐

从物化路径构建树

本文发布于:2023-10-15 02:52:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1493035.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:路径

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!