From: Ken Bloom Date: 2008-05-16T02:40:01+09:00 Subject: Re: Contionnal sum Xavier Noria wrote: > On Thu, May 15, 2008 at 6:26 PM, Fernando Perez 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/