0
0
Rubyprogramming~5 mins

Upto and downto methods in Ruby

Choose your learning style9 modes available
Introduction

The upto and downto methods help you count up or down between numbers easily.

When you want to repeat something from a smaller number up to a bigger number.
When you want to count down from a bigger number to a smaller number.
When you want to run a loop a certain number of times with numbers.
When you want to print numbers in order, either increasing or decreasing.
When you want to perform an action for each number in a range without writing a manual loop.
Syntax
Ruby
start.upto(end) do |variable|
  # code to run
end

start.downto(end) do |variable|
  # code to run
end

start and end are integers.

The block runs once for each number from start to end (inclusive).

Examples
This prints numbers from 1 to 5, counting up.
Ruby
1.upto(5) do |num|
  puts num
end
This prints numbers from 5 down to 1, counting down.
Ruby
5.downto(1) do |num|
  puts num
end
This runs the block once because start and end are the same.
Ruby
3.upto(3) do |num|
  puts num
end
Sample Program

This program shows how to count up and down using upto and downto.

Ruby
puts "Counting up from 1 to 4:"
1.upto(4) do |i|
  puts i
end

puts "Counting down from 4 to 1:"
4.downto(1) do |i|
  puts i
end
OutputSuccess
Important Notes

If start is greater than end in upto, the block does not run.

If start is less than end in downto, the block does not run.

Summary

upto counts up from a number to another number.

downto counts down from a number to another number.

Both run a block of code for each number in the range.