views:

101

answers:

2

For example:

for(int i = 0; i < 100; i += 2)

I could use a while loop or check if i % 2 == 0, but I was wondering if there wasn't a way to do it with the for loop. I could also use for(int i = 0; i < 50; i++) and multiply i by 2, but that doesn't seem right either. I'm just wondering if there is a simple, straightforward way to do it.

+10  A: 
(0...100).step(2) do |i|
  # loop body
end
sepp2k
out of interest, how would you translate `for(int i = 0; i < 100; i *= 2)` then?
oedo
@oedo: `i=0;while(true):`
mobrule
@mobrule: Good answer. =)
Arkku
@oedo: Not an exact translation, but Ruby 1.9 Enumerators are handy for such iterations: http://gist.github.com/365235
Mladen Jablanović
hahaha bedtime for me :P good answer mobrule :D
oedo
A: 

Ruby does not have a C style for loop -- which many feel is just a while loop in drag >:-}

Alternatives:

Use break

Use Ruby idioms like:

ar = [100, 200, 300, 500, 800]    # Arbitrary Array

# loop over each element of ar:                  
ar.each {|i|
  break if (500-i).abs == 0       # Arbitrary operation...
  puts i
}
drewk