Reputation: 203
So I'm new to ruby, I was practicing doing hackerrank excercices and when I had to sum an array I got the following 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 `'
Code:
def sum(n, arr)
sum = 0
for i in (0..n) do
sum += arr[i]
end
return sum
end
Similar js code:
const sum = function (n, arr) {
let sum = 0;
for (let i = 0; i < n; i++) {
sum += arr[i];
}
return sum;
};
Upvotes: 0
Views: 522
Reputation: 9
As others have noted, the best practice here is probably to just use the arr#each enumerable method (q.v.)
That aside: I'm not sure what your variable n is supposed to be, but I'm guessing it's the number of elements in your array. I'd offer that it's better practice to use the arr#length method (which returns the number of elements in the array; subtracting 1 syncs the loop with a zero-indexed array.)
test_arr = [1,2,3,4,5]
def sum(arr)
sum = 0
for i in (0..arr.length-1) do
sum += arr[i]
end
return sum
end
sum(test_arr) => 15
(FYI: Using arr.length is probably better practice in JavaScript as well (although using the JS .forEach or .reduce callback functions might be even better.))
for (let i = 0; i < arr.length -1; i++) {
Upvotes: 0
Reputation: 42192
Your n is bigger than the number of elements in your array-1 so it tries to sum a nil.
Here a better way to do this in Ruby, with an each in stead of a for which is seldom used. If you want to use a for, you could get the length of the array from arr.length instead of the parameter n.
def sum arr
sum = 0
arr.each do |e|
sum += e
end
sum
end
The real Ruby way would be the following. You inject a variable filled with 0 and enumerate each element of the array. The variables between the || are this variable, used to remember our sum and the element that is being enumerated.
[1,5].inject(0){|sum, e| sum + e }
=>6
or shorter
[1,5].inject(0, &:+)
=>6
or still better/shorter/readable (thus Ruby like) if you use Ruby 2.4
[1, 5].sum
=> 6
Upvotes: 4
Reputation: 755
The error is telling you that the addition operation is unsuccessful because one or more of the values is nil.
In this case, are you sure that when i==n
there will be a value at i[n]
?
Remember, arrays are 0-indexed. Meaning, if the length of the array is n, the index of the nth value will actually be n-1.
So when your loop hits n
, you end up trying to evaluate sum += nil
, which produces the error you are seeing.
Upvotes: 1