Error in summing the iteration of an array

0

I started in ruby these days and I have a question. I was doing the HackerRank exercises and in a certain exercise it was necessary to do the sum of the elements of the array, simple not? Yes. But my ruby code had an error message:

def sum(n, arr)
    sum = 0
    for i in (0..n) do
        sum += arr[i]
    end
    return sum
end

Error:

  

solution.rb: 6: in +': nil can't be coerced into Integer (TypeError) from solution.rb:6:in block in simpleArraySum '       from solution.rb: 5: in each' from solution.rb:5:in simpleArraySum '       from solution.rb: 15: in ''

JavaScript equivalent code:

const sum = function (n, arr) {
    let sum = 0;
    for (let i = 0; i < n; i++) {
        sum += arr[i];
    }
    return sum;
};
    
asked by anonymous 29.10.2017 / 00:18

1 answer

1

After searching a bit, I saw that I was changing the syntax, when I used% colon_with%, it means (0..n) is included in the iteration.

In this case you should have used n to not include it.

    
29.10.2017 / 02:31