-3

I am trying to sum array values. Here's my code:

def addArray(array)
  for i in array do
    sum += i
  end
end

addArray([1,3,6,8,7,10]);

What's wrong with this thought process? I know there are other ways to do this such as using reduce or even sum, but am I not just adding the next value to sum every iteration?

sawa
  • 165,429
  • 45
  • 277
  • 381
Rob
  • 63
  • 1
  • 14
  • 2
    Where did you define `sum` to be used in your method `addArray`? – Jagdeep Singh Jul 18 '18 at 07:19
  • 1
    On another note, the `for x in something do` syntax of enumerating in Ruby is not really the convention, and even according to the language developers, only still present in the language for legacy reasons. `array.each` would be the "standard way" to do it. Also note that the `for` syntax handles the scope differently than a normal block. – ForeverZer0 Jul 18 '18 at 07:46
  • You ask "What's wrong with this thought process?" That's not how [so] works. *You* need to tell us what's wrong, then we can help you fix it. Do you get an error message? If yes, what does it say, and what line does it occur on? Is the result you are getting not the result you are expecting? If yes, what result do you expect and why, what result do you get and why is that result not the correct one? Is the behavior you are observing not the behavior you are expecting? If yes, what behavior do you expect and why, what behavior do you observe instead and why is that behavior not the correct one? – Jörg W Mittag Jul 18 '18 at 10:04

3 Answers3

3

Your problem is that you don't have variable sum defined. In order to continue with the approach you've chosen, define the variable and return it after summation:

def add_array(array)
  sum = 0
  for i in array do
    sum += i
  end
  sum
end

puts add_array([1,3,6,8,7,10])
Igor Drozdov
  • 14,690
  • 5
  • 37
  • 53
0

As others have mentioned, you haven't defined the sum variable.

However, I feel it worth pointing out there's an existing Ruby method that handles this perfectly:

[1,3,6,8,7,10].reduce(:+) # => 35

For Ruby 2.4 onwards (or Rails), it's even easier:

[1,3,6,8,7,10].sum # => 35

reduce is a method used to iterate through values with an accumulator present. The above is shorthand for the following:

# `accumulator` is the equivalent of your `sum`, `element` your `i`
[1,3,6,8,7,10].reduce(0) do |accumulator, element|
  accumulator + element
end
SRack
  • 11,495
  • 5
  • 47
  • 60
0
def addArray(array)
  array.sum
end

I think this is the simplest answer.