好吧,我会说您的代码存在几个问题:
def go_to_child_ul_and_calculate(child_ul,summary_hash)
if child_ul.uls.none?
summary_hash.merge!(child_ul.id => "end of the line")
# 1. at this point eol is undefined
eol.push(child_ul.id)
return eol
else
# 2. you define eol here, but you actually call the method
# recursively again with the same parameters.
eol = go_to_child_ul_and_calculate(child_ul,summary_hash)
end
puts ":"
return eol
end
- 因为 eol 是一个局部变量,它是未定义的,所以这应该抛出一个错误(如果
if
语句评估为真)
- eol 应该是实例变量或通过方法参数提供。如果您使用相同的参数调用它,它并不是真正的递归方法。您可能希望在每个 child_nodes (
child_ul.uls
) 上调用它并合并结果。
可能的结果可能如下所示:(尽管我不得不说,递归算法中的变异参数看起来不太好,如果您在实际需要的内容上更简洁,我可以提供不同的方法。)
def go_to_child_ul_and_calculate(child_ul,summary_hash, eol=[])
if child_ul.uls.none?
summary_hash.merge!(child_ul.id => "end of the line")
eol.push(child_ul.id)
return eol
else
child_ul.uls.each do |ul|
go_to_child_ul_and_calculate(ul,summary_hash, eol)
end
end
puts ":"
return eol
end