Codectionary / Developer documentation / Ruby

Sliding Windows with each_cons

each_cons yields overlapping windows of a fixed size, useful for adjacent differences and rolling calculations. A sequence shorter than the window produces no complete windows. Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.

Syntax

values.each_cons(size) { |window| ... }

Examples

Sliding Windows with each_cons

Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.

readings = [10, 13, 12, 18]
changes = readings.each_cons(2).map { |before, after| after - before }
p changes
p readings.each_cons(3).to_a
  1. Expected output: [3, -1, 6] [[10, 13, 12], [13, 12, 18]]
  2. Each pair overlaps the previous pair by one reading. The three-element windows advance by one position each time.

Best practices

  • Use each_slice instead when nonoverlapping batches are required.
  • Choose a positive window size and consider memory use when collecting all windows.

Runtime & versions

Ruby interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Ruby documentation

Specifications & further reading