From: Mike Stok Date: 2013-06-25T08:44:01+09:00 Subject: Re: Sum method through while loops or iteration On 2013-06-24, at 7:33 PM, "Eric D." 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) > > array = [] > > while array >0 > array.each { |a| sum+=a } > > 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 = [2, 4, 6, 9, 11] sum = 0 array.each { |val| sum += 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 > > 2. > > def sum > x= [] > x.each{|element| element +element } > > end > > 3. > def sum(array) > > while array.length > 0 > puts "#{array[x+y+z]}" > else > puts "0" > > -- > Posted via http://www.ruby-forum.com/. -- Mike Stok http://www.stok.ca/~mike/ The "`Stok' disclaimers" apply.