Ruby | Integer upto() function
Last Updated :
04 Dec, 2020
The upto function in Ruby returns all the numbers from a given to number itself. It iterates the given block, passing in increasing values from number1 up to number2. If no block is given, an Enumerator is returned instead.
Syntax: (number1).upto(number2)
Parameter: The function takes number1 and number2 which is the range in which the numbers are returned. It also takes a block.
Return Value: The function returns all the numbers from number1 to number2 itself.
Example 1:
Ruby
num1 = 8 num2 = 12
puts num1.upto(num2)
{
| i | print i, " "
}
num3 = 5 num4 = 15
puts num3.upto(num4)
{
| i | print i, " "
}
|
Output:
8 9 10 11 12 8
5 6 7 8 9 10 11 12 13 14 15 5
Example 2:
Ruby
num1 = 1 num2 = 3
puts num1.upto(num2)
{
| i | print i, " "
}
num3 = - 7 num4 = - 2
puts num3.upto(num4)
{
| i | print i, " "
}
|
Output:
1 2 3 1
-7 -6 -5 -4 -3 -2 -7
Example 3:
Ruby
num1 = 1 num2 = 3
puts num1.upto(num2)
|
Output:
#
Reference: https://devdocs.io/ruby~2.5/integer#method-i-upto
Share your thoughts in the comments
Please Login to comment...