红宝石 |可枚举的 each_cons()函数
enumerable的each_cons()是 Ruby 中的内置方法,每次从每个元素开始迭代连续的 N 个元素。如果没有给出块,则返回枚举数。
Syntax: enu.each_cons(N) { |obj| block }
Parameters: The function takes the block which is used to check the condition and N which specifies the number of consecutive elements to take.
Return Value: It returns the elements iterative consecutive for each element.
示例 1 :
# Ruby program for each_cons method in Enumerable
# Initialize
enu = (1.. 5)
# returns each element
enu.each_cons(2){|obj| p obj}
输出:
[1, 2]
[2, 3]
[3, 4]
[4, 5]
示例 2 :
# Ruby program for each_cons method in Enumerable
# Initialize
enu = (1..10)
# returns each element
enu.each_cons(4)
输出:
Enumerator: 1..10:each_cons(4)