Re: Contionnal sum
Xavier Noria <fxn <at> hashref.com> wrote:
> On Thu, May 15, 2008 at 6:26 PM, Fernando Perez <pedrolito <at> lavache.com> wrote:
>
>> I am wondering if it is possible to create a conditionnal sum.
>>
>> For instance I would like to do something like this:
>>
>> @total_amount = @orders.sum { |order| order.amount if order.paid == true
>> }
>
> sum... is that Rails? If that's the case you could filter them before:
>
> # untested
> @total_sum = @orders.select(&:paid).sum(&:amount)
>
> Although AR has another SQL-based #sum that may be worth exploring if
> @orders are ARs.
>
> That being said, perhaps you weren't aware of the fact that
> Enumerable#sum is defined by Active Support, but let me point out that
> those extensions are discussed in the very Rails mailing list.
Enumerable#sum is also in facets.
The .select method is a good way, but you can use less memory by doing
@orders.sum {|order| order.paid? order.amount : 0 }
Facets' #sum doesn't skip nils, so the method you proposed won't work.
--Ken
(Continue reading)