Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 509
Jason Varga Avatar asked Mar 07 '13 16:03

Jason Varga


3 Answers

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

or

items.map(&:sale_price).sum(&:to_i)
like image 176
dbenhur Avatar answered Nov 19 '22 16:11

dbenhur


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.

like image 43
DigitalRoss Avatar answered Nov 19 '22 16:11

DigitalRoss


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

like image 3
benchwarmer Avatar answered Nov 19 '22 18:11

benchwarmer