digitxp digitxp - 6 months ago 24
Ruby Question

Start a loop from 1

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

Answer

Ruby supports a number of ways of counting and looping:

1.upto(10) do |i|
  puts i
end

>> 1.upto(10) do |i|
 >     puts i
|    end #=> 1
1
2
3
4
5
6
7
8
9
10

There's also step instead of upto which allows you to increment by a step value:

>> 1.step(10,2) { |i| puts i } #=> 1
1
3
5
7
9
Comments