Ruby | Enumerable each_cons() function
Last Updated :
05 Dec, 2019
The each_cons() of enumerable is an inbuilt method in Ruby iterates for consecutive N elements starting from each element every time. If no block is given, it returns the enumerator.
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.
Example 1:
enu = ( 1 .. 5 )
enu.each_cons( 2 ){|obj| p obj}
|
Output:
[1, 2]
[2, 3]
[3, 4]
[4, 5]
Example 2:
enu = ( 1 .. 10 )
enu.each_cons( 4 )
|
Output:
Enumerator: 1..10:each_cons(4)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...