Skip to content

End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

Enumerable#each_cons

enum.each_cons(n) { ... } → nil
enum.each_cons(n) → an_enumerator

Iterates the given block for each array of consecutive <n> elements. If no block is given, returns an enumerator.

e.g.:

Example
(1..10).each_cons(3) { |a| p a }
# outputs below
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
[4, 5, 6]
[5, 6, 7]
[6, 7, 8]
[7, 8, 9]
[8, 9, 10]
See also #drop_while #each_entry #drop #each_slice also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.1