From: Florian Gilcher Date: 2009-12-03T10:45:39+09:00 Subject: Re: Increment outerloop value in innerloop in each do Syntax On Dec 2, 2009, at 9:28 PM, Nag Raj wrote: > Hi All, > > I am new to RUBY. Please help me in solving the below problem. > I have a c code and I am trying to do the same in RUBY. > > for(int i = 0; i < 10;i++) > { > for(int j = 0; j< 5; j++) > { > if(i == j) > { > printf("%d - its J value\n",j); > i++; > } > } > printf("%d - its I value\n",i); > } Wow, is there any use case for this pattern? > > I want to do the same in RUBY. I have written following script > > (0..9).each do |i| > (0..5).each do |j| > if( i == j) > puts "#{j} J Value" > end > end > puts "#{i} I Value" > 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