我的卖家模型有很多项目。
我想获得所有卖家商品的总销售价格。
在seller.rb中我有
def total_item_cost
items.to_a.sum(&:sale_price)
end
如果所有商品具有销售价格,这都可以
但是,如果它们尚未售出,则sale_price
为零,而total_item_cost
会中断。
在我的应用中,sale_price
可以是零或零。
在我的total_item_cost
方法中,如何将nil
值视为零?
答案 0 :(得分:48)
items.map(&:sale_price).compact.sum
或
items.map(&:sale_price).sum(&:to_i)
答案 1 :(得分:34)
一种方法是:
items.to_a.sum { |e| e.sale_price.to_i } # or to_f, whatever you are using
#to_f
和#to_i
等方法会将nil
变为0
。
答案 2 :(得分:3)
拒绝零值。 items.to_a.reject{|x| x.sales_price.nil?}.sum(&:sale_price)