15 May 18:47
Re: Contionnal sum
From: Xavier Noria <fxn <at> hashref.com>
Subject: Re: Contionnal sum
Newsgroups: gmane.comp.lang.ruby.general
Date: 2008-05-15 16:47:29 GMT
Subject: Re: Contionnal sum
Newsgroups: gmane.comp.lang.ruby.general
Date: 2008-05-15 16:47:29 GMT
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.
-- fxn
RSS Feed