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?
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
And then:
t = a.inject(Tree.new) { |t, h| t.add(h) }
h = t.root
would give this in 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.