将模型对象分组并计算 min/max/count

Group model objects by and calculate min/max/count

我正在尝试按名称和品牌分组并获得价格的最小值、价格的最大值、价格的平均值和价值计数。这是活动模型,不是活动记录。

型号:

class Product
  include ActiveModel::Model
  attr_accessor :name, :brand, :price, :value
end

预期输出:

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

请帮忙。

代码:

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 do |product|
  [product.name , product.brand]
end

grouped_products.map do |_, 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