From: Brian Candler Date: 2007-04-19T04:18:46+09:00 Subject: Re: Recursive method not working On Thu, Apr 19, 2007 at 01:05:05AM +0900, Zouplaz wrote: > Hi, I'm trying to display a hierarchical tree but there's something > wrong with the method below. > The result var is 'lost' between the calls - I mean, each "#{result}" > contains the right value at the end of the method (I checked that), but > that value is lost when returning to the upper level. > > I don't see why... > > Thanks for your help ! > 1> def affiche_arbre(rubriques) 2> for rubrique in rubriques 3> result = '
' 4> 0.step(rubrique.level) { result += ' '} 5> result += rubrique.libelle + ' ' + link_to('+', :action => 'new', :parent_id => rubrique) + ' ' 6> unless rubrique.parent_id == nil 7> result += link_to('E', :action => 'edit', :id => rubrique) + ' ' + link_to('D', :action => 'delete', :id => rubrique ) 8> end 9> if rubrique.children.size > 0 10> result += affiche_arbre(rubrique.children) 11> end 12> end 13> "#{result}" 14> end Well, the only recursive call I can see is line 10. You append the return values from these calls onto 'result'. But then in line 12 you go back around the loop, and in line 3 you reinitialise result, thereby throwing away everything you've calculated so far.