Ruby | Enumerable each_slice() function
The each_slice() of enumerable is an inbuilt method in Ruby iterates for each range of N elements and prints them. If no block is given, then it returns the enumerator.
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.
Example 1:
# Ruby program for each_slice method in Enumerable # Initializeenu = (1.. 5) # returns sliceenu.each_slice(2){|obj| p obj} |
Output:
[1, 2] [3, 4] [5]
Example 2:
# Ruby program for each_slice method in Enumerable # Initializeenu = (1..10) # returns each element enu.each_slice(4) |
Output:
Enumerator: 1..10:each_slice(4)


.png)