From: Matthew Smillie Date: 2006-07-04T04:15:37+09:00 Subject: Re: Array loops: new thread On Jul 3, 2006, at 19:27, Dark Ambient wrote: > I thought it would be better to start a new thread for my current > issue, since the old one is filled with code in various stages. > Apologies. Gives me a chance to ask more succinctly regarding the > core issue. > > This is just an example. > I have 2 arrays > > firstarray = ['1','2,'3','4','5'] > secondarray = ['1','2','3','4','5','6','7'] > > I'm looping through firstarray.each do |x| > go through some blocks. At some point, either the start of the outter > array or somewhere down in the conditional statements I need to find > out if elements of firstarray are in secondarray. The only way I can > fathom doing this right now is by starting another loop, i.e. > secondarray.each do |y|. Problem is this seems to create constant > problems where the outter loop / [0] element is going through the > entire inner loop before proceeding on. to it's next element. Maybe > as someone suggested earlier today to me, to use break. Haven't had > much luck with that yet. If you don't want to use loops at all, you could use the intersection operator: overlap = firstarray & secondarray If you do want to use loops (which would be good practice for you), then just be careful to remember what each loop is doing. While using include? or the intersection operator wouldn't hurt anything, given your trouble with nesting loops it's probably good practice to learn how to do them properly - they're an incredibly common construct in programming, and if you don't learn how to build them for something simple you could get very stuck later on. Even your simple file comparison example wouldn't work using include?, since the filenames include different directories. The basic idea you should remember is that you can write the inner loop as if it were a normal loop working with a single variable. For example, if the outer loop is "firstarray.each do |first|" then you can write the inner loop as if you had this: first = 1 secondarray.each do |second| # do things with first and second here. end Here's a simple example which tells you exactly what it's doing: firstarray = [1, 2, 3] secondarray = [1, 3, 5] overlap = [] firstarray.each do |first| puts "Outer loop setting first = #{first}" # we want to compare first to everything in the second array: secondarray.each do |second| puts "\tInner loop setting second = #{second}" print "\tComparing #{first} to #{second}..." if first == second puts "matched!" # do what we need to when we find a match overlap.push(first) # if you *know* there's a max of 1 match, # you could put a break here to stop looking # for more matches. else puts "no match." end end puts "\tInner loop finished." end puts "Outer loop finished." puts overlap matthew smillie.