Ruby | Enumerable each_slice() function
Last Updated :
05 Dec, 2019
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:
enu = ( 1 .. 5 )
enu.each_slice( 2 ){|obj| p obj}
|
Output:
[1, 2]
[3, 4]
[5]
Example 2:
enu = ( 1 .. 10 )
enu.each_slice( 4 )
|
Output:
Enumerator: 1..10:each_slice(4)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...