On 2013-06-24, at 7:33 PM, "Eric D." <lists / ruby-forum.com> wrote:

> I am trying to create a sum method for an empty array, that will =
return
> "0" if there is nothing in it and the sum of the values if there are
> values called through it. I have seen other ways on the internet, but =
I
> am relatively new to this, and am under the impression that this can =
be
> done with while loops or .each iteration. Below are various things I
> tried, some were actual thoughts some were out of sheer frustration.
> Thanks for your help!
> 1.
> def sum (array)
>=20
> array =3D []
>=20
> while array >0
> array.each { |a| sum+=3Da }
>=20
> end

It can be done with loops, and you need to think through what you are =
trying to do.

Maybe:

1) Initialize the sum to 0
2) For each value in the array, add that value to the sum

which translates into ruby something like this:

array =3D [2, 4, 6, 9, 11]

sum =3D 0
array.each { |val| sum +=3D val }

puts "sum is #{sum}"

would be a place to start, and then you can package it up into a method, =
once you understand what each line does.

There are other ways to do it, but you should master the basics so you =
can understand the more advanced methods.

Hope this helps,

Mike

>=20
> 2.
>=20
> def sum
> x=3D []
> x.each{|element| element +element }
>=20
>  end
>=20
> 3.
> def sum(array)
>=20
>  while array.length > 0
>    puts "#{array[x+y+z]}"
>  else
>    puts "0"
>=20
> --=20
> Posted via http://www.ruby-forum.com/.

--=20

Mike Stok <mike / stok.ca>
http://www.stok.ca/~mike/

The "`Stok' disclaimers" apply.