From: Kevin Brown Date: 2005-12-08T16:39:07+09:00 Subject: Re: increasing counter whithin loop? On Wednesday 07 December 2005 18:07, Patrick Gundlach wrote: > [...] > OK, then it makes sense that one cannot manipulate counter. But IMO it > is not intuitive (POLS ;-)) that the counter in the for-loop can't be > changed. Don't base your sense of "intuitive" on other languages. It is more intuitive that we're going through each element in an array than checking an arbitrary integer against a condition in between two semicolons, IMHO. And my first real language was C++. The generally "normal" way to do string processing in Ruby is with Regular Expressions. This is arguable, but at least I've seen it more. Play with my gsub example and see if you can't get something in one line that does what you're looking for (unless you haven't told us the real situation). > > 90% of the time you don't need counters or while loops, though. > > Even here, there's nothing preventing you from doing e.g.: > > > > skip = false > > sequence.each do |element| > > if skip > > skip = false > > next > > end > > ... > > # set skip to true to skip the next iteration > > ... > > end > > Yes, sure, but now it is getting ugly again. I am not looking for any > way to work, but to find a readable, beautiful and ruby-like piece of > code. Use RegExps to do your string processing then. I admit, it's just NOT the way you think about string processing when coming from something like C++, but it's so much easier to say "Find all the repeated letters and replace them with double 'letter'" than "loop through every letter in the string. If the next letter in the string is the same as the current one, then replace both of them with 'double letter' by making a new array, copying the current over, replacing the letters, copying the end over, and then incrementing the count of the for loop to get the language structure to support what I happen to be doing." When you're used to the latter, it's hard to get your head around regexps, but it's much nicer, IMHO, and I'm one that had to do the adjustment. Play with it and see if you can't get something that works, or let us know what you're really doing, and I'm sure that someone will pop out with a golfed intuitive one-ish-liner that fixes your problem. :-) > Patrick