Treating nil as zero in sum function

后端 未结 3 441
遥遥无期
遥遥无期 2020-12-15 04:37

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         


        
相关标签:
3条回答
  • 2020-12-15 05:10
    items.map(&:sale_price).compact.sum
    

    or

    items.map(&:sale_price).sum(&:to_i)
    
    0 讨论(0)
  • 2020-12-15 05:10

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

    0 讨论(0)
  • 2020-12-15 05:13

    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.

    0 讨论(0)
提交回复
热议问题