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

Beginner array iteration & error code interpretation

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

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

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

  1. 为什么要修复它?我唯一的猜测是最初使用 (<=) 使其迭代 "too far" 并因此以某种方式返回 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。如果您尝试对同一个引用执行操作(未在 nil.methods 中列出),它将抛出您看到的错误。