Q:

Treating nil as zero in sum function

I have a Seller model that has_many Items.
I want to get the total sale price of all of a Seller's items.
In seller.rb I have
def total_item_cost 
  items.to_a.sum(&:sale_price)
end

This works fine if all the items have a sale price.
However, if they haven't been sold yet, sale_price is nil and the total_item_cost breaks.
In my app, sale_price can be either a nil or a zero.
In my total_item_cost method, how can I treat nil values as zeros?

A:

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

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

A:

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

Methods like #to_f and #to_i will turn nil into 0.

A:

Reject the nil values. items.to_a.reject{|x| x.sales_price.nil?}.sum(&:sale_price)

