I need help with aggregating (summing) grouped structures

class DetailInfo 
      attr_accessor :material,:det_length, :det_width, :det_thick
    
      def initialize(material, det_length, det_width, det_thick)
        @material = material
        @det_length = det_length
        @det_width = det_width
        @det_thick = det_thick    
      end
end

details =[
	DetailInfo .new("Material1", 760, 340, 18),
	DetailInfo .new("Material1", 800, 200, 18),
	DetailInfo .new("Material1", 760, 340, 4),
	DetailInfo .new("Material1", 800, 200, 4),		
	DetailInfo .new("Material2", 400, 440, 16),
	DetailInfo .new("Material2", 800, 200, 16),
]

grouped_details = details.group_by {|detailinfo| [detailinfo.material, detailinfo.det_thick]}
squares = grouped_details.map do |material, det_length, det_width|
  square = details.reduce(0) { |sum, detailinfo| sum + detailinfo.det_length*detailinfo.det_width}
  { material: material, sq: square.round(3) }
end

puts squares

#-----------------------------------------------------  
{:material=>["Material1", 18], :sq=>1172800}
{:material=>["Material1", 4], :sq=>1172800}
{:material=>["Material2", 16], :sq=>1172800}

Why do all groups have the same values?

Please edit your post and correctly delimit the code for forum display …

There are already posts that cover this subject. Use the search feature :mag: of the forum on this category.

Use the term “area”

1 Like