Library contents

Ruby Enumerable#group_by

group_by creates a hash whose values are arrays of the original elements grouped by the block's result.

A simple example

Enumerable#group_by

  1. Start with 1, 2, 3
  2. Do this Group by odd or even
  3. Result Odd [1, 3], even [2]
Each number is collected under the key produced by the grouping rule.

Syntax

Ruby syntax
orders.group_by { |order| order[:region] }
Run this example in Ruby

Save the program as lesson.rb. Use Ruby 2.6 or later.

ruby lesson.rb

Group orders while preserving each order record

An export contains keys that may identify more than one input record. Establish what happens at a repeated key before constructing the lookup so useful records are not discarded unintentionally.

First output lineeast=7
lesson.rb
orders = [{region: 'east', qty: 3}, {region: 'west', qty: 1}, {region: 'east', qty: 4}]
groups = orders.group_by { |order| order[:region] }
%w[east west north].each do |region|
  total = groups.fetch(region, []).sum { |order| order[:qty] }
  puts "#{region}=#{total}"
end
Output
east=7
west=1
north=0

The group retains all matching records. Hash#fetch with an empty array as fallback makes an unseen region produce an empty group for reporting.

Ruby documentation for Enumerable#group_by

Advertisements

Fill the east-studio tote

A courier sorts parcels into destination totes as the labels arrive. Append each parcel to the list for its destination. In what order do the parcels appear in the selected group?

GivenEast P4 · West P8 · East P2
Worked resultP4 · P2

Prepare a library transfer

Three crates arrive for different branches at the sorting desk. Append each parcel to the list for its destination. In what order do the parcels appear in the selected group?

GivenHill C8 · Park C2 · Hill C9
Worked resultC8 · C9