'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?
Solution 1:[1]
items.map(&:sale_price).compact.sum
or
items.map(&:sale_price).sum(&:to_i)
Solution 2:[2]
Reject the nil values. items.to_a.reject{|x| x.sales_price.nil?}.sum(&:sale_price)
Solution 3:[3]
Assuming sales_price is a column in the DB:
items.sum(:sales_price)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dbenhur |
| Solution 2 | |
| Solution 3 | Chris Habgood |
