From: "Michael W. Ryder" <_mwryder@...> Date: 2007-03-20T14:30:08+09:00 Subject: Re: C(++) For Loop Equivalents Raj Sahae wrote: > studlee2 wrote: >> What is the most efficient way in Ruby to create a conditional loop in >> Ruby that looks like this in C(++): >> >> for(int i=0; i*j/2> { >> //cool method stuff >> } >> >> >> I was looking at the .upto() method but it doesn't like the comparison >> operator :-/ >> >> Thanks > Why not just do: > ((maxNum*2)/(i*j)).times do |n| > #cool method stuff > end > He would need to initialize i before your code as it could be any value, not just 0. By the same token the increment could be any number, not just 1. A further problem with your method is that the loop is executed until i*j/2 is greater than maxNum. As you don't know if the loop somehow modifies the value of j you can not optimize it out. A simple example would be where the program reads some numbers from a file and adds them to j. i is incremented by one each time a number is read. You want the program to exit when i*j/2 is larger than maxNum.