From: Kevin Brown Date: 2005-12-08T04:22:33+09:00 Subject: Re: increasing counter whithin loop? On Wednesday 07 December 2005 11:51, mental@rydia.net wrote: > Quoting Patrick Gundlach : > > This is why I thought > > > > for i in sequence > > if sequence[i]=='b' and sequence[i+1]=='b' > > output 'double b' > > # increase i, so that the second 'b' won't be seen by the > > for-loop > > # but ruby won't let me!? > > # i += 1 does nothing > > else > > output sequence[i] > > end > > end > > > > would work, but I can't change the i in the for-loop. This is a > > pity! > > It's probably helpful to realize that Ruby has no for-loop in the > traditional sense. The above is equivalent to: > > sequence.each do |i| > if sequence[i]=='b' and sequence[i+1]=='b' > output 'double b' > # increase i, so that the second 'b' won't be seen by the > for-loop > # but ruby won't let me!? > # i += 1 does nothing > else > output sequence[i] > end > end > > Written this way, it's probably more obvious why incrementing i > doesn't do what you had expected. > > -mental If you're really tied to the traditional for loop, you can use a while loop and do the increment yourself at the end of the loop, but usually you find a better way to do it in Ruby that doesn't involve going through the chars one at a time, and that's why we rarely use the for construct.