Skip to content

Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →

instance method

Enumerable#each_cons

each_cons(n) { ... } → self
each_cons(n) → enumerator

Calls the block with each successive overlapped n-tuple of elements; returns self:

Example
a = []
(1..5).each_cons(3) {|element| a.push(element) }
a # => [[1, 2, 3], [2, 3, 4], [3, 4, 5]]

a = []
h = {foo: 0,  bar: 1, baz: 2, bam: 3}
h.each_cons(2) {|element| a.push(element) }
a # => [[[:foo, 0], [:bar, 1]], [[:bar, 1], [:baz, 2]], [[:baz, 2], [:bam, 3]]]

With no block given, returns an Enumerator.

Ruby version changes

  1. 3.1
    • Enumerable#each_cons and each_slice to return a receiver. [GH-1509]

      Example
      [1, 2, 3].each_cons(2){}
      # 3.0 => nil
      # 3.1 => [1, 2, 3]
      
      [1, 2, 3].each_slice(2){}
      # 3.0 => nil
      # 3.1 => [1, 2, 3]
      
See also #drop_while #each_entry #drop #each_slice also in 4.1 · 4.0 · 3.4 · 3.2 · 3.1 · 3.0