将nil作为和函数处理为零

我有一个卖家模型has_many项目。

我想得到所有卖家商品的总销售价格。

在seller.rb我有

def total_item_cost items.to_a.sum(&:sale_price) end 

如果所有商品都有售价,这样可以正常使用。
但是,如果它们尚未售出,则sale_price为零且total_item_cost中断。

在我的应用中, sale_price可以是零或零。

在我的total_item_cost方法中,如何将nil值视为零?

一种方法是:

 items.to_a.sum { |e| e.sale_price.to_i } # or to_f, whatever you are using 

#to_f#to_i这样的方法会将nil变为0

 items.map(&:sale_price).compact.sum 

要么

 items.map(&:sale_price).sum(&:to_i) 

拒绝零值。 items.to_a.reject{|x| x.sales_price.nil?}.sum(&:sale_price)