Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start a loop from 1

Tags:

loops

ruby

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 
like image 269
Casey Chow Avatar asked Apr 24 '11 20:04

Casey Chow


People also ask

How do you start a loop with 1?

If you want a loop to start at 1 , you have to initialize the loop variable with 1 . Or, you "normalize" your loop variable when using them in an expression, e.g. x + 1 to produce a value offset by 1 (i.e. 1-11 in your example).

Does a for loop start at 1?

A for loop can start with 0 or 1 or -1 or 37 or whatever.

Does for loop start 0 or 1?

Most loops starts with 0.

Can Python loop start at 1?

To loop through a set of code a specified number of times, we can use the range() function, The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.


2 Answers

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 
like image 58
the Tin Man Avatar answered Oct 08 '22 23:10

the Tin Man


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

like image 37
mu is too short Avatar answered Oct 08 '22 23:10

mu is too short