红宝石 |可枚举的 each_slice()函数
enumerable的each_slice()是 Ruby 中的一个内置方法,它对 N 个元素的每个范围进行迭代并打印它们。如果没有给出块,则返回枚举器。
Syntax: enu.each_slice(N) { |obj| block }
Parameters: The function takes the block which is used to check the condition and N which specifies the number of elements to take in a single slice.
Return Value: It returns the elements in N slices.
示例 1 :
# Ruby program for each_slice method in Enumerable
# Initialize
enu = (1.. 5)
# returns slice
enu.each_slice(2){|obj| p obj}
输出:
[1, 2]
[3, 4]
[5]
示例 2 :
# Ruby program for each_slice method in Enumerable
# Initialize
enu = (1..10)
# returns each element
enu.each_slice(4)
输出:
Enumerator: 1..10:each_slice(4)