Simon Krahnke | 15 May 19:35

Re: Contionnal sum

* Fernando Perez <pedrolito <at> lavache.com> (18:26) schrieb:

> Hi,
>
> 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
> }

@total_amount = @orders.inject(0) do | sum, order |
  order.paid ? sum + order.amount : sum
end

or

@total_amount = @orders.select { | o | o.paid }. sum

BTW: Comparing a boolean value to true or false only shows you don't
understand booleans.

And if that order class is yours: I'd rather call the accessor »paid?«.

mfg,                    simon .... l


Gmane