ruby on rails - Group model objects by and calculate min/max/count -
i trying group name , brand , minimum value of price, maximum value of price, average value of price , count value. activemodel, not active record.
model:
class product include activemodel::model attr_accessor :name, :brand, :price, :value end expected output:
name:"big", brand:"sony", price_min:10, price_max:10, price_avg:10, count_value:2 name:"small", brand:"car", price_min:10, price_max:13, price_avg:11.5, count_value:2 name:"round", brand:"car", price_min:14, price_max:14, price_avg:14, count_value:1 name:"horse", brand:"car", price_min:10, price_max:10, price_avg:10, count_value:1 please help.
code:
myarray = [] myarray << product.new({name: "big", brand: "sony", price: 10, value: 5}) myarray << product.new({name: "big", brand: "sony", price: 10, value: 2}) myarray << product.new({name: "small", brand: "car", price: 13, value: 3}) myarray << product.new({name: "small", brand: "car", price: 10, value: 4}) myarray << product.new({name: "round", brand: "car", price: 14, value: 5}) myarray << product.new({name: "horse", brand: "car", price: 10, value: 6}) myarray
grouped_products = myarray.group_by |product| [product.name , product.brand] end grouped_products.map |_, v| [ [ :name, v[0].name ], [ :brand, v[0]. brand ], [ :price_min, v.min_by { |p| p.price }.price ], [ :price_max, v.max_by { |p| p.price }.price ], [ :price_avg, v.sum { |p| p.price } / v.count ], [ :count_value, v.count ] ].to_h end
Comments
Post a Comment