将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)