I recently came upon the scary idea that Integer.count
loops in Ruby start from 0
and go to n-1
while playing with the Facebook Engineering puzzlers. I did the dirty fix of adding one to the block variable in the beginning so that it would start at one instead.
Is there a prettier way?
Example:
10.times do |n|
n += 1
puts n
end #=> 012345789
Try
instead. It is also easier to read when the value of
i
matters.Ruby supports a number of ways of counting and looping:
There's also
step
instead ofupto
which allows you to increment by a step value:There is of course the
while
-loop:Old, but this might be something somebody's lookin for..
You could use a range:
Ranges give you full control over the starting and ending indexes (as long as you want to go from a lower value to a higher value).