Open In App

Ruby | Enumerable each_slice() function

Last Updated : 05 Dec, 2019
Comments
Improve
Suggest changes
Like Article
Like
Report
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
# Ruby program for each_slice method in Enumerable

# Initialize
enu = (1.. 5)

# returns slice
enu.each_slice(2){|obj| p obj}
Output:
[1, 2]
[3, 4]
[5]
Example 2: Ruby
# Ruby program for each_slice method in Enumerable

# Initialize
enu = (1..10)

# returns each element 
enu.each_slice(4)
Output:
Enumerator: 1..10:each_slice(4)

Next Article

Similar Reads