gpt4 book ai didi

ruby - 从物化路径构建树

转载 作者:数据小太阳 更新时间:2023-10-29 07:32:52 24 4
gpt4 key购买 nike

我在使用 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"] }
]}
]}

谁能帮帮我?

最佳答案

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

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

如果它们很重要,您可以整理出空的 :children

关于ruby - 从物化路径构建树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7795682/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com