Ruby Enumerable#chunk
Group consecutive equal statuses while preserving the sequence in which updates arrived.
A simple example
Enumerable#chunk
- Start with A, A, B, A
- Do this Group consecutive equal entries
- Result AA, B, A
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.rbCount 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.
statuses = %w[ready ready sent ready]
statuses.chunk { |status| status }.each do |status, run|
puts "#{status}: #{run.size}"
end
ready: 2 sent: 1 ready: 1
The last ready opens a new run because sent interrupts the earlier pair.
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?
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?
What to watch for
For totals over the whole list regardless of position, use a frequency table instead.