Forum: Ruby on Rails How to add up an array's element with a rails way?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Cf82fcc4825dd733c0365eb504291c6f?d=identicon&s=25 Kevin Fu (Guest)
on 2009-06-05 09:17
(Received via mailing list)
Hi,

I have a method like this, calculating the sub_total in an order model:

def sub_total
  result = 0
  for item in self.order_items
    result += item.price
  end
  result
end

Is there a rails way to make the method more simple and concise?

Thank you :)

--
regards,
Kai Fu

Material Science and Engineering
Huazhong University of Science and Technology
Wuhan Hubei Province P.R.China
E-mail: corntrace@gmail.com
81b61875e41eaa58887543635d556fca?d=identicon&s=25 Frederick Cheung (Guest)
on 2009-06-05 09:21
(Received via mailing list)
On Jun 5, 5:01 am, Kevin Fu <corntr...@gmail.com> wrote:
> end
>
> Is there a rails way to make the method more simple and concise?
>

Have a peak at the sum method :-)

Fred
4ab2692ba129cb296d4f2e90ba5241da?d=identicon&s=25 Sandip Ransing (san2821)
on 2009-06-05 09:53
(Received via mailing list)
use active record sum method

self.order_items.sum( :price )

-Sandip

On Fri, Jun 5, 2009 at 12:50 PM, Frederick Cheung <
frederick.cheung@gmail.com> wrote:

> >   for item in self.order_items
> Fred
> >
>


--
Ruby on Rails Developer
http://sandip.sosblog.com
http://funonrails.wordpress.com
www.joshsoftware.com
This topic is locked and can not be replied to.