Re: increasing counter whithin loop?
- From: mental@xxxxxxxxx
- Date: Thu, 8 Dec 2005 08:08:23 +0900
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
.
- Follow-Ups:
- Re: increasing counter whithin loop?
- From: Patrick Gundlach
- Re: increasing counter whithin loop?
- References:
- increasing counter whithin loop?
- From: Patrick Gundlach
- Re: increasing counter whithin loop?
- From: Patrick Gundlach
- Re: increasing counter whithin loop?
- From: mental
- Re: increasing counter whithin loop?
- From: Kevin Brown
- Re: increasing counter whithin loop?
- From: Patrick Gundlach
- increasing counter whithin loop?
- Prev by Date: Re: Standard Library questions
- Next by Date: Re: Ruby newcomer
- Previous by thread: Re: increasing counter whithin loop?
- Next by thread: Re: increasing counter whithin loop?
- Index(es):
Relevant Pages
|