From: Nag Raj Date: 2009-12-04T00:47:29+09:00 Subject: Re: Increment outerloop value in innerloop in each do Syntax Florian Gilcher wrote: > On Dec 2, 2009, at 9:28 PM, Nag Raj wrote: > >> { >> printf("%d - its J value\n",j); >> i++; >> } >> } >> printf("%d - its I value\n",i); >> } > > Wow, is there any use case for this pattern? > >> end > Be aware that i or j are in no way the same as i and j in > your C program. Here, you iterate over the set of natural > numbers from 0..9 and 0..5, binding i and j to those values > for every step of the iteration. So i and j are not controlling > your iteration - each does. > So any change to i and j will be lost at the end of the do-block. > > But, with a bit of trickery, you can achieve this: > > (0..9).each do |i| > if j = (0..5).find{ |j| i==j } > puts "#{j} J Value" > else > puts "#{i} I Value" > end > end > > #find finds the first element of the range that satisfies > the condition given in the block. If there is none, it returns > nil, which is not true in a boolean sense. As the statement in > the condition can be any ruby expression (because the always return > a value, there is no void), we can immediately assign that to j. > > As j has a true value (everything but nil and false) if the find > condition matches, the first branch of the if is used. Otherwise, > j is nil and i is printed. > > Again: you iterate over a set, this is no counting loop. This might > take a bit to get used to, but in the end, you can use such nice > things as #find, #map, #inject on it. Learn them, they are a rubyists > mightiest tools. > > Have a lot of fun. > > Regards, > Florian Gilcher Hi All, Thank you very much Michael and Florian for your help. I am sorry John if I made something wrong. I tried with continue, break and next. Nothing worked out for me. Unluckily I have to insert some code according to this pattern. Because remaining file maintained this format so I have to. At last after some manipulation, I got the below code which works similar to the above codes given by Michael and Florian. Once again thank you very much for the help. myval = true (0..9).each do |i| (0..5).each do |j| if(i==j) puts "#{j} its J value" myval = false end end if(myval) puts "#{i} its I value" end myval = true end Regards, Nag -- Posted via http://www.ruby-forum.com/.