From: Brandon Weaver Date: 2012-09-18T13:03:32+09:00 Subject: Re: how to sum element of array --f46d042de40b29c87b04c9f1f982 Content-Type: text/plain; charset=ISO-8859-1 On Mon, Sep 17, 2012 at 9:27 PM, Padma J. wrote: > Edward QU wrote in post #1074559: > > dear all > > > > a_array=[2,4,6,8,10] > > I want to sum the elements of the array: > > 2+4+6+8+10 > > how to write the script? > > > > many thanks! > > best regards > > Edward > > Hi Edward, > > You could also use the inject method from the Enumerable module like > this: > > array.inject(0) { |sum, i| sum+i } > > Cheers. > > -- > Posted via http://www.ruby-forum.com/. > > You could also use a shorter version of inject: array.inject(:+) --f46d042de40b29c87b04c9f1f982 Content-Type: text/html; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable

On Mon, Sep 17, 2012 at 9:27 PM, Padma J= . <lists@ruby-forum.com> wrote:
Edward QU wrote in post #1074559:
> dear all
>
> a_array=3D[2,4,6,8,10]
> I want to sum the elements of the array:
> 2+4+6+8+10
> how to write the script?
>
> many thanks!
> best regards
> Edward

Hi Edward,

You could also use the inject method from the Enumerable module like
this:

=A0 array.inject(0) { |sum, i| sum+i }

Cheers.

--
Posted via http://= www.ruby-forum.com/.


You could also use a shorter vers= ion of inject:

array.inject(:+)
--f46d042de40b29c87b04c9f1f982--