# Ruby puzzle: Group candies by unique record fields

**URL:** <https://www.ruby-forum.com/t/ruby-puzzle-group-candies-by-unique-record-fields/79835>\
**Category:** Ruby\
**Created:** [December 19, 2006, 5:04pm UTC](https://www.ruby-forum.com/t/ruby-puzzle-group-candies-by-unique-record-fields/79835 "2006-12-19T17:04:53Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![wogaswoga](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/w/71e660/32.png) [@wogaswoga](https://www.ruby-forum.com/u/wogaswoga)\
**Post date:** [December 19, 2006, 5:04pm UTC](https://www.ruby-forum.com/t/ruby-puzzle-group-candies-by-unique-record-fields/79835/1 "2006-12-19T17:04:53Z")

</div>

I have an list of objects (Candy) and each object has two fields  
(Candy.color, Candy.taste). I would like to display the candies but  
group them based on the fields (display a header for each group). The  
problem is I don’t know how many colors or tastes are in any particular  
list of candies.

This is what I have for input:

- Candy \<-- hash list already pre-sorted by “group”
- group \<-- variable contains either “color” or “taste”

Can anyone come up with a ruby code snipet that will use the “group”  
variable to extract out the group labels (unique values of the color or  
tate field), and then dump out the Candy list by group.

Really appreciate your help!

---

<div class="post-metadata">

**Author:** ![wogaswoga](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/w/71e660/32.png) [@wogaswoga](https://www.ruby-forum.com/u/wogaswoga)\
**Post date:** [December 20, 2006, 2:51pm UTC](https://www.ruby-forum.com/t/ruby-puzzle-group-candies-by-unique-record-fields/79835/2 "2006-12-20T14:51:53Z")

</div>

Woga Swoga wrote:

> Can anyone come up with a ruby code snipet that will use the “group”  
> variable to extract out the group labels (unique values of the color or  
> tate field), and then dump out the Candy list by group.
> 
> Really appreciate your help!

Not sure if your Candy list is actually a hash or just an array of Candy  
objects. I’ll write the code assuming the later.

group\_flag = false  
group\_flag = true if group == “color”  
grouping = {}

candy.each do |piece|  
element = piece.color if group\_flag  
element = piece.taste if !group\_flag  
grouping[element] ||= []  
grouping[element] \<\< piece  
end

grouping.each do |key,element|  
puts “Grouping: #{key}”  
element.each do |piece|  
puts " "+candy.name  
end  
end
