Ruby 整数时间函数与示例
Ruby 中的times函数返回从 0 到比数字本身小一的所有数字。它迭代给定的块,传入从 0 到限制的递增值。如果没有给出块,则返回一个枚举器。
Syntax: (number).times
Parameter: The function takes the integer till which the numbers are returned. It also takes an block.
Return Value: The function returns all the numbers from 0 to one less than the number itself.
示例 #1:
# Ruby program for times function
# Initializing the number
num1 = 8
# Prints the number from 0 to num1-1
puts num1.times { |i| print i, " " }
# Initializing the number
num2 = 5
# Prints the number from 0 to num2-1
puts num2.times { |i| print i, " " }
输出 :
0 1 2 3 4 5 6 7
0 1 2 3 4
示例 #2:
# Ruby program for times function
# Initializing the number
num1 = 4
# Prints the number from 0 to num1-1
puts num1.times { |i| print i, " " }
# Initializing the number
num2 = -2
# Prints the number from 0 to num2
puts num2.times { |i| print i, " " }
输出:
0 1 2 3
-2
示例#3:
# Ruby program for times function
# Initializing the number
num1 = 5
# Prints enumerator as no block is given
puts num1.times
输出:
#