Kevin Brown
12/7/2005 10:24:00 PM
On Wednesday 07 December 2005 16:07, Patrick Gundlach wrote:
> [...]
>
> > 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.
>
> That is exactly what I am trying to find. I have a list (Array) of
> different elements, which I want to render below each other, except
> when there are two elements of type 'b', they can be put next to each
> other. So I think I need a check like 'if this element is == 'b' and
> next element is also == 'b', then render them next to each other. This
> rendering has to be known in advance, so I can't use information if
> the last element is of type 'b' (with the second occurance of 'b').
>
> Of course, I can write a while loop, but this would be
>
> a) setting some counter to 0
> b) accessing the elements via [] (index)
> c) checking on counter <=> sequence.length
>
> all which are acceptable, but don't look like the nice ruby builtins
> that I am used to. The
>
> 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? Is there any reason why we can't manipulate the
> counter within the loop?
No, you can manipulate the counter just fine, just that it won't persist for
the next iteration of the count. This is because ruby is providing the i for
you, but not actually checking it to know where it is, or when it's done,
unlike similarly worded constructs in C etc.
How about something like:
irb(main):008:0> "abbcdeef".gsub(/(\w)\1/) { |match|
irb(main):009:1* " double #{match[0, 1]} "
irb(main):010:1> }
=> "a double b cd double e f"