初学者数组迭代和错误代码解释



我一直收到以下错误。经过一些研究,我认为这是因为我的数组访问由于(错误地)具有 NIL 值而抛出错误。

my_solution.rb:24:in `count_between': undefined method `>=' for nil:NilClass       
(NoMethodError) from my_solution.rb:35:in `<main>'

我是阅读错误代码的新手,所以也许这就是我出错的地方。但正如错误所暗示的那样,它在 24 行获得了隧道视野。但是我无法修复它,所以出于绝望,我最终随机将第 23 行的 (<=) 更改为 (<)。这修复了它。

  1. 为什么会修复它?我唯一的猜测是最初使用 (<=) 使其迭代"太远",因此以某种方式返回 NIL?

  2. 为什么错误代码说是第 24 行的元素导致了问题,而实际上是第 23 行的元素?我是新手,正试图减少错误代码的困扰,所以这是一次奇怪的经历。

感谢您的任何指导。

# count_between is a method with three arguments:
#   1. An array of integers
#   2. An integer lower bound
#   3. An integer upper bound
#
# It returns the number of integers in the array between the lower and upper          
# bounds,
# including (potentially) those bounds.
#
# If +array+ is empty the method should return 0
# Your Solution Below:
def count_between(list_of_integers, lower_bound, upper_bound)
if list_of_integers.empty?
   return 0
else
   count = 0
   index = 0
   ##line 23## 
   while index <= list_of_integers.length
   ##line24## 
       if list_of_integers[index] >= lower_bound &&    
       list_of_integers[index] <= upper_bound
            count += 1
            index += 1
       else
            index += 1
       end
    end 
 return count
end
end
puts count_between([1,2,3], 0, 100)

<= list_of_integers.length的最后一个索引在数组之外,因为数组的第一个索引是 0,最后一个索引是 array.length - 1

您的错误显示第 24 行的原因是第 23 行工作正常,---它只是计算 index 的值小于或等于数组的长度。但是,一旦您尝试引用数组中该索引处的元素,它就会被分配为 nil - 并且您无法对 nil 执行>=操作。

这里有一件事可能会有所帮助,那就是启动一个 irb。如果你尝试引用一个越界的元素,你只会得到零。如果您尝试对同一引用执行操作(未在nil.methods中列出),它将引发您看到的错误。

最新更新