From: Mike Harris Date: 2007-01-12T06:49:11+09:00 Subject: Re: A loop within another loop.. Dominic Son wrote: >Hi. Hopefully you will see the code and see what I'm trying to do, and >see the problem. The loop seems messy, but my method to help with eye >strain is to match up the do-end's down an imaginary column... ie: > >array.each # do # |i| > puts i # # <-imaginary column > # end # > >##### So here's the code. ########### > >def foo(argument1, argument2) #1 >user = [2,5] > >user.each do |bar| >output = [] #2 >argument1.each do |i| #3 > > if i.parent.id == bar.id #4 > output << i.parent.name > end > end > > argument2.each do |i| > if i.parent.id == bar.id > output << i.name > end > end >return output > end > >Comments: >#1 - argument comes in as arrays >#2 - let's setup the var that will return the array of collected data >#3 - i think this is where the problem may lie. >#4 - parent is an acts_as_tree method inside rails, just grabs the >parant. > notice how i call the iterating variable 'bar' inside this new >loop..is this legal? > >My intuition tells me there's probably a better method to do this. Any >comments, suggestions would be appreciated. > >Dominic > > > First, your code is missing an end. Second, making the end to the block start is easy with the standard convention (with the missing end added in) def foo(argument1, argument2) #1 user = [2,5] user.each do |bar| output = [] #2 argument1.each do |i| #3 if i.parent.id == bar.id #4 output << i.parent.name end end end argument2.each do |i| if i.parent.id == bar.id output << i.name end end output end This is infinitely easier (to me, and 99.9% of programmers) than moving the end out to match the do. Do you find this hard to read? You seem to have no problem matching the end to its matching if.