将模型对象分组并计算最小/最大/计数

时间:2016-01-27 20:05:13

标签: ruby-on-rails ruby model activemodel

我正在尝试按名称和品牌进行分组,并获得最低价格,最高价格价格,平均价格和价值计数。这是activemodel,不是活动记录。

型号:

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

1 个答案:

答案 0 :(得分:2)

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