Ruby puzzle: Group candies by unique record fields

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!

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