对括号内的变量和数字求和时出错 NoMethodError

Error when summing variable and number inside brackets NoMethodError

我不知道为什么会出现下面提到的错误。这是因为我使用了一个变量并将其与括号内的数字相加。我该如何解决? 任何帮助将不胜感激。我花了很多时间寻找答案,但找不到。非常感谢!

代码是这样的:

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
)

错误:

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

恕我直言,这行代码导致了问题

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

如果 nums = [1, 2, 3] 那么长度是 3; when i = 2 then b = 3When b = 3 然后 nums[b] (nums[3]) is nil.

可能的解决方案

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

错误是 'b' 没有递增。我在第二个 while 中添加了 'b += 1' 并且比较中的 '=' 导致提到 djaszczurowski,我将其删除。谢谢!

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
      b += 1
    end
    i += 1
  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

)