Xavier Noria
5/15/2008 4:47:00 PM
On Thu, May 15, 2008 at 6:26 PM, Fernando Perez <pedrolito@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