Bac*_*het 6 ruby methods recursion ruby-on-rails helper
我想显示一个用宝石祖先管理的类别树.
我想使用一个帮助器,它将递归地遍历树并逐个返回类别,暂时没有html标签或内容.
module CategoriesHelper
def display_tree(category)
if category.has_children?
category.children.each do |sub_category|
display_tree(sub_category)
puts(sub_category.name) # to check if it goes here
end
end
category.name
end
end
Run Code Online (Sandbox Code Playgroud)
该category参数是根类别之一.
应该归还什么?
Sport Beauty AutomobileMen Indoor Women Children Water sport Garage如果得到它们,则意味着递归有效,但事实并非如此.为什么它只返回第一次迭代?
另外,我想按以下顺序获取它们:
root/child/child-of-child
Run Code Online (Sandbox Code Playgroud)
但如果我想回来category.name,它应该在最后一个位置.
你能告诉我你的意见吗?
PS:我刚刚发现(在添加标签期间)我在搜索中一直使用"递归"这个词,但它不存在,即使很多人在stackOveflow上使用它; o) - >"递归",但是我还是被困住了
**编辑**
现在我使用这段代码:
module CategoriesHelper
def display_tree(category)
tree = "<div class =\"nested_category\">#{category.name}"
if category.has_children?
category.children.each do |sub_category|
tree += "#{display_tree(sub_category)}"
end
end
tree += "</div>"
end
end
Run Code Online (Sandbox Code Playgroud)
这给了我:
<div class ="nested_category">Sport
<div class ="nested_category">Men</div>
<div class ="nested_category">Women
<div class ="nested_category">Indoor</div>
</div>
<div class ="nested_category">Children</div>
<div class ="nested_category">Water sport</div>
</div>
<div class ="nested_category">Beauty</div>
<div class ="nested_category">Automobile
<div class ="nested_category">Garage</div>
</div>
Run Code Online (Sandbox Code Playgroud)
但该html未被解释,并且显示的网页中显示相同的代码.我的意思是,我明白了
我可能错过了一些东西......也许是知识oO
谢谢
您正在使用的方法将仅返回一个值(实际上是对category.name的第一次调用)关于控制台,您将获得循环内的puts(这不是方法的返回值)。
尝试一下,如果还有什么地方不够清楚,请告诉我:
module CategoriesHelper
def display_tree(category)
tree = category.name
if category.has_children?
category.children.each do |sub_category|
tree += "/#{display_tree(sub_category)}"
end
end
tree
end
end
Run Code Online (Sandbox Code Playgroud)