Ruby | Enumerable each_cons() function

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program for each_cons method in Enumerable
  
# Initialize
enu = (1.. 5)
  
# returns each element 
enu.each_cons(2){|obj| p obj}

chevron_right


Output:

[1, 2]
[2, 3]
[3, 4]
[4, 5]

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program for each_cons method in Enumerable
  
# Initialize
enu = (1..10)
  
# returns each element 
enu.each_cons(4)

chevron_right


Output:

Enumerator: 1..10:each_cons(4)


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.