Ruby on Rails 3.2.2, Ruby 1.9.3
I have array data from Siz.requirements.all (model)
model fields (siz,heigth,wigth,kol)
[{:siz=>10, :heigth = 30, :wigth = 20, :kol = 24},
{:siz=>10, :heigth = 30, :wigth = 10, :kol = 24},
{:siz=>10, :heigth = 30, :wigth = 20, :kol = 33},
{:siz=>10, :heigth = 20, :wigth = 20, :kol = 3},
{:siz=>10, :heigth = 20, :wigth = 20, :kol = 5},...
how create array or hash with group by fields
for example:
[{:siz=>10 => {:heigth=>"30" => {:wigth=>"20" => {:sum_kol => sum(kol)}}},
{:siz=>10 => {:heigth=>"30" => {:wigth=>"10" => {:sum_kol => sum(kol)}}},
{:siz=>10 => {:heigth=>"20" => {:wigth=>"20" => {:sum_kol => sum(kol)}}}]
If this is coming from a database, I would look at using the database to do the grouping and summarizing for you. But here’s one way to do it in Ruby:
Normally it would more idiomatic in Ruby to use
inject/reduceinstead of the initialization + update loop:But with the default-laden hash and the need to return the hash at the end of the reduce block, I think the original version is cleaner here.