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- Expected output: [3, -1, 6] [[10, 13, 12], [13, 12, 18]]
- 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