Iterating upto and downto

If you need 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:

upto_downto.rb

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

The previous code displays the integers 0 to 10. You may also count down from a high to a low value using the downto() method:

10.downto(0) do
    | i |
    puts( i )
end

As you can probably guess, this code displays 10 to 0.

Get The Book of Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.