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 | #   w  w  w  . j a va 2 s .com
    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 | # from   w  w  w  .ja  v  a 2s. c  om
    puts( i ) 
end

Result

Related Topic