Introduction
The upto and downto methods help you count up or down between numbers easily.
The upto and downto methods help you count up or down between numbers easily.
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).
1.upto(5) do |num| puts num end
5.downto(1) do |num| puts num end
3.upto(3) do |num| puts num end
This program shows how to count up and down using upto and downto.
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
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.
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.
5.upto(8) do?upto methodupto method counts upwards from the starting number to the ending number, including both.5.upto(8)upto counts up = A [OK]downto in Ruby?downto starting at 10 and ending at 7.10.downto(7) { |i| puts i } correctly counts down and prints each number.sum = 0
3.upto(5) { |i| sum += i }
puts sum3.upto(5) iterates over 3, 4, 5.5.upto(3) { |i| puts i }upto method behaviorupto counts up from start to end. Here start=5, end=3, which is invalid for counting up.downto, how can you create an array of even numbers counting down from 10 to 2?downto starting at 10 and ending at 2.if i.even? to add only even numbers to the array.Pass the test and this pattern moves unknown