我有一个深度嵌套的哈希,其中混合了数组。哈希表示关系图。每个节点可以与下一个节点建立一个或多个连接。
输入/输出: 示例:
Given {'id' => biology}
results_should_be: {'biology' => {'id' => biology, 'paths' => [[{'id' => biology}]]}}
Given {'id'=> biology, 'children' =>[{'id' => microbiology}, {'id' => physicalbio}]}
results_should_be:
{'biology' => {'id' => biology, 'paths' => [['id' => biology]]},
"microbiology"=>{"id" => "microbiology", "paths" => [[{"id" => "biology"}, {"id" => "microbiology"}]]},
"physicalbio"=>{"id" => "physicalbio", "paths" => [[{"id" => "biology"}, {"id" => "physicalbio"}]]}
Given {'id'=> biology, 'children' =>[{'id' => microbiology, 'children' => [{'id' => physicalbio},{"id" => "physicalbio"}]}}
results_should_be:
{'biology' => {'id' => biology, 'paths' => [['id' => biology]]},
"microbiology"=>{"id" => "microbiology", "paths" => [{"id" => "biology", "id" => "microbiology"}]},
"physicalbio"=>{"id" => "physicalbio", "paths" => [[{"id" => "biology"}, {"id" => "physicalbio"}][{"id" => "biology"}, {"id" => "microbiology"},{"id" => "physicalbio"}]]}
我的测试结果失败
{"biology"=>{"id"=>"biology", "paths"=>[[{"id"=>"biology"}]]},
"microbiology"=>
{"id"=>"microbiology",
"children"=>[{"id"=>"physicalbio", "paths"=>[[{"id"=>"microbiology"}, {"id"=>"physicalbio"}], [{"id"=>"biology"}, {"id"=>"microbiology"}, {"id"=>"physicalbio"}]]}],
"paths"=>[[{"id"=>"biology"}, {"id"=>"microbiology"}]]},
"physicalbio"=>{"id"=>"physicalbio", "paths"=>[[{"id"=>"biology"}, {"id"=>"physicalbio"}]]}}
代码块
def build_concept_with_paths(concept,parent_id=nil)
concept['paths'] = []
parent_id.nil? ? concept['paths'] << [concept['id']] : concept['paths'] << [{'id' => parent_id}, {'id' =>concept['id']}]
concept
end
def build_concept_data(concepts)
concepts.keys.first(2).each_with_object({}) do |k,data|
if k == 'children'
concepts[k].each do |concept|
child = build_concept_with_paths(concept,concepts['id'])
data[child['id']] = child
if concept['children']
build_concept_data(child)
end
end
concept_id = concepts[k]
concept = {'id' => concept_id,'paths' => [[{'id' => concept_id }]] }
data[concepts[k]] = concept
end
end
end
我的递归调用,似乎没有影响最终结果,我无法从递归中返回结果。任何帮助都会很棒。