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
- Start with 1, 2, 3
- Do this Group by odd or even
- Result Odd [1, 3], even [2]
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.
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
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
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?
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?