Library contents

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

  1. Start with 1, 2, 3
  2. Do this Take each adjacent pair
  3. Result [1, 2] and [2, 3]
The next window starts one element later, so the middle value appears twice.

Syntax

Ruby 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.

From the programreadings = [5, 8, 6]
First output line3,-2
lesson.rb
readings = [5, 8, 6]
changes = readings.each_cons(2).map { |before, after| after - before }
puts changes.join(',')
puts [5].each_cons(2).count
Output
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

Advertisements

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?

Given4 → 8 → 7 → 9
Worked result3

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?

Given5 → 12
Worked result1