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: ineach' 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;
};