红宝石 |可枚举的循环()函数
enumerable的cycle()是 Ruby 中的一个内置方法,它为 enum 的每个元素重复调用块给定的数字次,如果没有给出或给出 nil,则永久调用。如果给出负数或集合为空,则它什么也不做。如果循环完成而没有被中断,则返回 nil。如果没有给出块,则返回一个枚举器。
Syntax: block.cycle(times) { |obj| block }
Parameters: The function takes the block according to which the every block is to be returned. Also it takes the times which signifies the number of times it has to be executed. If times is not given it executes infinitely.
Return Value: It returns the enumerator N times which satisfies the given condition of the block.
示例 1 :
# Ruby program for cycle method in Enumerable
# Initialize
enu = [12, 18]
# returns cycle
res = enu.cycle(3) { |el| puts el*4 }
输出:
48
72
48
72
48
72
示例 2 :
# Ruby program for cycle method in Enumerable
# Initialize
enu = [12, 18]
# returns cycle
res = enu.cycle(3)
输出:
Enumerator: [12, 18]:cycle(3)