On Mon, Mar 3, 2008 at 6:10 AM, Cory C. [email protected] wrote:
I’m new to Ruby. Is there such thing as a C++ style (and most others)
for loop in Ruby? What I mean by that is:
for( init, while-condition, increment ) { function-here }
Simply put, no, Ruby has nothing that works quite like the C-style for
loop.
I know I can do that with a while loop, but I enjoy the compactness of
the above statement.
Usually, there is a simpler compact idiom using the iterator methods in
the
Enumerable module or specific container classes like Array if you need
something more compact than a while loop.
There are many times where Ruby’s for-each loops
just don’t do the trick.
The main looping tehcnique in Ruby is using iterator methods. You
could make something like the C-style for loop using them, with the
caveat
that all the loop parameters have to be specified as proc objects. It
would
be something like (this is code from the top of my head):
module Kernel
def cfor (init, condition, increment)
init.call
while condition.call
yield
increment.call
end
end
end
But, even if proc objects didn’t make calling this a little ugly,
you really don’t need it: there is generally a better more specific
way of doing things in Ruby.
For instance, in the example you give later in the thread:
a = some_array
minValue = 999999
for(i=0; i<a.length && minValue!=0; i+=1) {
minValue = (5000 - a[i]).abs
}
You seem to want to find the index of the first item in the array
that equals 5000 (which is what the value of i is when you bail
out) or the absolute value of 5000 minus the last item value in
the area (what minValue is if you fail to bail out).
so:
a = some_array
i = a.index(5000) || a.length
minValue = (i<a.length) ? 0 : (5000-a.last).abs
You can probably do something more elegant depending on
what you are doing with the results.
Also, is there anything like i++ or do I always have to do i=i+1 ?
You can do i+=1, i=i.succ, or i=i.next, if you prefer, but Ruby doesn’t
have
the increment or decrement operators of the C family.