Library contents

Ruby Enumerable#chunk

Group consecutive equal statuses while preserving the sequence in which updates arrived.

A simple example

Enumerable#chunk

  1. Start with A, A, B, A
  2. Do this Group consecutive equal entries
  3. Result AA, B, A
The last A begins a new group because B interrupted the run.

Syntax

Ruby syntax
statuses.chunk { |status| status }
Run these examples in Ruby

Save one example at a time as lesson.rb. Use Ruby 2.6 or later.

ruby lesson.rb

Count runs of delivery statuses

A reporting system receives a sequence of events or product codes with repetitions. Aggregate the values according to the required grouping and order so the report keeps the distinction between items and occurrences.

First output lineready: 2
lesson.rb
statuses = %w[ready ready sent ready]
statuses.chunk { |status| status }.each do |status, run|
  puts "#{status}: #{run.size}"
end
Output
ready: 2
sent: 1
ready: 1

The last ready opens a new run because sent interrupts the earlier pair.

Advertisements

Group consecutive bus zones

Stops are recorded in travel order and a zone can appear again later. Group adjacent equal codes as one run. How many runs appear in the sequence?

GivenA · A · B · A
Worked result3

Group kiln readings by status

The studio receives three consecutive ready signals. Group adjacent equal codes as one run. How many runs appear in the sequence?

GivenR · R · R
Worked result1

What to watch for

For totals over the whole list regardless of position, use a frequency table instead.

Documentation for Enumerable#chunk