Reputation: 3659
I'm trying to write very simple recursive method, but can't make it work. I have simple comments hierarchy with ids like here:
1--
2--
4--
3--
5--
Now I want to save their ids in array (tree order) [0]=1, [1]=2, [2]=4, [3]=3, [4]=5
I start building this array in Entry model with
def comment_tree
comment = self.comments.find(1) #it's temporary, just to check if it works
return recur(comment,0)
end
private
def recur(comment,i)
@tree[i]=comment.id #added attr_accessible :@tree
if comment.children.any?
comment.children.each {|c| recur(c,i+1)}
else
return
end
@tree
end
This doesn't work, as block runs twice the same counter argument recur(4,2)
and recur(3,2)
. I need something like global $i to keep this arras index, but I'm sure there must be better way of doing it. The same is with @tree, do I really have to add new variable to model just to use it as a return parameter from recur method? I won't use it in any other place.
Upvotes: 1
Views: 373
Reputation: 5398
How about this:
def comment_tree
comment = self.comments.find(1)
tree = []
recur(comment, tree)
tree
end
private
def recur(comment, acc)
acc << comment.id
comment.children.each {|c| recur(c, acc) }
end
Upvotes: 2