从物化路径构建树
我在使用 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" }
]
我只需要它作为 ruby 中的树,以下哈希就足够了:
{ :title => "Home", :path => [], :children => [
{ :title => "About", :path => ["about"] },
{ :title => "Services", :path => ["services"], :children => [
{ :title => "Plans", :path => ["services", "plans"] }
]}
]}
有人可以帮助我吗?
I have a trouble building a tree structure from materialized path using ruby.
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"] }
]}
]}
Could anyone help me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您只需要一个简单的帮助器类和一点递归即可:
然后:
将在
h
中给出:如果重要的话,您可以整理出空的
:children
。A simple helper class and a bit of recursion is all you need:
And then:
would give this in
h
:You can sort out the empty
:children
if they matter.