Error when summing variable and number in parentheses NoMethodError

advertisements

I don't know why the error mentioned below happens. It is caused because I use a variable and summing it with a number inside the brackets. How can I fix it? Any help would be greatly appreciated. I have spent much time searching for the answer but I couldn't find it. Thank so much!

The Code is this:

def two_sum(nums)
  i = 0
  while i < nums.length
    b = i + 1
    while b <= nums.length
      if nums[i] + nums[b] == 0
        puts("we need to store this numbers")
      elsif
        puts("It doesn't match")
      end
      i += 1
    end
  end
end

# These are tests to check that your code is working. After writing
# your solution, they should all print true.

puts(
  'two_sum([1, 3, 5, -3]) == [1, 3]: ' + (two_sum([1, 3, 5, -3]) == [1, 3]).to_s
)
puts(
  'two_sum([1, 3, 5]) == nil: ' + (two_sum([1, 3, 5]) == nil).to_s
)

Error:

08-two-sum.rb:06:in `two_sum': undefined method `+' for nil:NilClass (NoMethodError)
from 08-two-sum.rb:23:in `<main>'


IMHO this line of code causes problem

if nums[i] + nums[b] == 0

in case when nums = [1, 2, 3] so length is 3; when i = 2 then b = 3. When b = 3 then nums[b] (nums[3]) is nil.

possible solution

def two_sum(nums)
  i = 0
  while i < nums.length
    b = i + 1
    while b <= nums.length
      num_i = nums[i]
      num_b = nums[b] || 0

      if (num_i + num_b) == 0
        puts("we need to store this numbers")
      elsif
        puts("It doesn't match")
      end
      i += 1
    end
  end
end