Ruby - Iterating upto and downto

Introduction

To count from a specific low value up to a high value, you may use the upto() method of an integer.

A block argument may optionally be used if you want to display the value at each iteration:

Demo

0.upto(10) do 
    | i | # from  w ww .  ja va 2  s  .co  m
    puts( i ) 
end

Result

The previous code displays the integers 0 to 10.

To count down from a high to a low value using the downto() method:

Demo

10.downto(0) do 
    | i | # w  w  w .  jav  a 2  s .co  m
    puts( i ) 
end

Result

Related Topic