Start a loop from 1

RubyLoops

Ruby Problem Overview


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

Ruby Solutions


Solution 1 - Ruby

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

Solution 2 - Ruby

You could use a range:

(1..10).each { |i| puts i }

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).

Solution 3 - Ruby

Try

(1..10).each do |i|
 #  ... i goes from 1 to 10
end

instead. It is also easier to read when the value of i matters.

Solution 4 - Ruby

Old, but this might be something somebody's lookin for..

5.times.with_index(100){|i, idx| p i, idx};nil
#=>
    0
    100
    1
    101
    2
    102
    3
    103
    4
    104

Solution 5 - Ruby

There is of course the while-loop:

i = 1
while i<=10 do
  print "#{i} "
  i += 1
end
# Outputs: 1 2 3 4 5 6 7 8 9 10

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCasey ChowView Question on Stackoverflow
Solution 1 - Rubythe Tin ManView Answer on Stackoverflow
Solution 2 - Rubymu is too shortView Answer on Stackoverflow
Solution 3 - RubyKathy Van StoneView Answer on Stackoverflow
Solution 4 - RubyRyoView Answer on Stackoverflow
Solution 5 - RubyParnab SanyalView Answer on Stackoverflow