Re: increasing counter whithin loop?



Quoting Patrick Gundlach <clr9.10.randomuser@xxxxxxxxxxxxxxx>:

> sequence.each do |element|
> ....
> end
>
> would be nice, but I understand that there is no
> 'skip_the_next_element'-method. So the next nicer attempt would
> be
>
> for counter in 0...element.size
> # ...
> increase_counter_by_one_to_skip_one_interation
> end
>
> But - contradicting my intuition - doesn't seem to work/exist. So
> I have to stick to an ugly while loop.... ;-) So my question is:
> did I miss something?

There's really no difference between:

for counter in 0...element_size
...
end

and

(0...element_size).each do |counter|
...
end

Both call Range#each with the given block.

> Is there any reason why we can't manipulate the counter within
> the loop?

'counter' isn't actually a counter. It's just a parameter of the
block given to Range#each. While there's probably a real counter
behind the scenes somewhere, it's not exposed to you.

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

or alternately:

skip = false
sequence.each do |element|
unless skip
...
# set skip to true to skip the next iteration
...
end
skip = false
end

-mental


.



Relevant Pages

  • Yow! LOOP macros are LOOPY!
    ... By relying entirely on procedure calls to express iteration, ... to but cleaner than C's FOR loop. ... other macros going around at the time other than MacLisp's ... (bind (vi (vector-ref v i))) ...
    (comp.lang.scheme)
  • Re: Polling, Interrupts, DMA, Synchronous, Asynchronous I/O Definitions
    ... the terminology is less useful than it might be. ... though a "message loop" could arguably be claimed to be ... considering in a particular iteration but what is true for _ALL_ ... watching the "polling" version eating up every single CPU cycle ...
    (alt.lang.asm)
  • Re: Histogram of character frequencies
    ... generated object code may simply be a loop in which elements are ... believe any C compiler anywhere would reject it. ... On the first iteration of the loop you test the end of file indicator ...
    (comp.lang.c)
  • Re: Random number help
    ... is used to generate cooccurance matrix for each iteration of for loop. ... disp('the sample co-occurance matrix is as follows');% GIVING SAME ...
    (comp.soft-sys.matlab)
  • Re: LOOP blows!
    ... The order of initialization follows the ... There are two `initializations' in execution of LOOP, ... before staring the first iteration. ... |> The first for clause will never terminate. ...
    (comp.lang.lisp)