Sum error in an array iteration

Asked

Viewed 40 times

0

I started at Ruby the other day 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 array elements, not simple? 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:inblock in simpleArraySum' from Solution.Rb:5:in each' from solution.rb:5:insimpleArraySum' 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;
};

1 answer

1


After searching a little about it I saw that I was changing the syntax, when used (0..n) with two points means that the n is included in the iteration.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.