15 May 19:40
Re: Contionnal sum
From: Ken Bloom <kbloom <at> gmail.com>
Subject: Re: Contionnal sum
Newsgroups: gmane.comp.lang.ruby.general
Date: 2008-05-15 17:40:01 GMT
Subject: Re: Contionnal sum
Newsgroups: gmane.comp.lang.ruby.general
Date: 2008-05-15 17:40:01 GMT
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
--
--
Ken (Chanoch) Bloom. PhD candidate. Linguistic Cognition Laboratory.
Department of Computer Science. Illinois Institute of Technology.
http://www.iit.edu/~kbloom1/
RSS Feed