Ruby Enumerable#each_cons
each_cons yields overlapping groups of a fixed size. With a size of two it exposes every adjacent pair without a manual index.
A simple example
Enumerable#each_cons
- Start with 1, 2, 3
- Do this Take each adjacent pair
- Result [1, 2] and [2, 3]
Syntax
values.each_cons(2) { |before, after| ... }
Run this example in Ruby
Save the program as lesson.rb. Use Ruby 2.6 or later.
ruby lesson.rb
Compare every adjacent pair of readings
A meter produces readings in a sequence where neighboring values matter. Compare the relevant adjacent samples or windows in their original order to determine how the signal changes over time.
readings = [5, 8, 6]
changes = readings.each_cons(2).map { |before, after| after - before }
puts changes.join(',')
puts [5].each_cons(2).count
3,-2 0
An input shorter than the window yields no groups. Overlap matters here because the middle reading participates in both changes.
Ruby documentation for Enumerable#each_cons
Compare consecutive meter samples
A class records a series of four readings. Take adjacent pairs with a one-place step. How many pairs can the report compare?
Compare two shift counts
The supervisor has an opening and a closing count. Take adjacent pairs with a one-place step. How many pairs can the report compare?