From: Daniel Finnie Date: 2007-03-20T10:27:53+09:00 Subject: Re: C(++) For Loop Equivalents Use the step method: ----------------------------------------------------------- Numeric#step num.step(limit, step ) {|i| block } => num ------------------------------------------------------------------------ Invokes _block_ with the sequence of numbers starting at _num_, incremented by _step_ on each call. The loop finishes when the value to be passed to the block is greater than _limit_ (if _step_ is positive) or less than _limit_ (if _step_ is negative). If all the arguments are integers, the loop operates using an integer counter. If any of the arguments are floating point numbers, all are converted to floats, and the loop is executed _floor(n + n*epsilon)+ 1_ times, where _n = (limit - num)/step_. Otherwise, the loop starts at _num_, uses either the +<+ or +>+ operator to compare the counter against _limit_, and increments itself using the +++ operator. 1.step(10, 2) { |i| print i, " " } Math::E.step(Math::PI, 0.2) { |f| print f, " " } _produces:_ 1 3 5 7 9 2.71828182845905 2.91828182845905 3.11828182845905 So your example would become: 0.step(i*j/2, 1) # (I'm not too sure about the details of C++ and if defining i in the beginning would make i*j/2 be 0 no matter what) Or, you could do 0.upto(i*j/2) # assumes step is one. Finally, you could do for i in 0..(i*j/2) do |i| # blah... end Daniel Sheppard 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 >> } > > In the general case, you can 'while' anywhere where you'd normally 'for' > > i=0 > while i*j/2 //cool method stuff > i++ > end > > But 'most efficient way' to do a conditional loop depends on your > context (and also what you're trying to make efficient - runtime? > writetime? readtime?). > > Dan. > >