Reputation: 8086
Trying to sum up all the numbers in an array. Example 10 + 20 + 30 should be 60.
def sum *arr
i=0
total=0
while i <= arr.count
total += arr[i]
i+=1
end
total
end
puts sum(10,20,30)
Why am I getting this error. This code looks like it should work to me. What am I doing wrong? Why wont it let me access the array value by it's index?
p8.rb:23:in `+': nil can't be coerced into Fixnum (TypeError)
from p8.rb:23:in `sum'
from p8.rb:29:in `<main>'
Upvotes: 1
Views: 69
Reputation: 1
Matt's answer is both slick and correct, but you hit the error because ruby zero indexes arrays. So if you changed the count condition
while i <= arr.count - 1
your error would go away
Upvotes: 0
Reputation: 2664
Matt's answer gives you the canonical Ruby way to sum, using inject. But if you're not ready to learn inject, at least save yourself the trouble of manually keeping track of array indexes (where your actual problem lies!) by using #each to iterate through the array like so:
def sum *arr
total = 0
arr.each do |x|
total += x
end
total
end
puts sum(10,20,30) # => 60
Upvotes: 1
Reputation: 20776
Change
while i <= arr.count
to
while i < arr.count
arr[arr.count]
is always out of bounds.
Fyi a shorter way to write sum
is:
def sum *arr
arr.inject(:+)
end
Upvotes: 7