我不断收到以下错误。经过一些研究后,我认为这是因为我的数组访问错误(错误地)是由于有一个NIL值。初学者数组迭代和错误代码解释
my_solution.rb:24:in `count_between': undefined method `>=' for nil:NilClass
(NoMethodError) from my_solution.rb:35:in `<main>'
我是新来读的错误代码,所以也许这就是我出错的地方。但是,由于错误提示,它在线上获得了隧道视觉。然而我无法修复它,所以无奈之下,我随即将(< =)行随机更改为(<)。这固定了它。
这是为什么解决它?我唯一的猜测是最初使用(< =)使它迭代“太远”,从而以某种方式返回NIL?
错误代码为什么说它是第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)
[1,2,3] .length => 3但是数组索引从0开始,所以要遍历一个数组,您可以这样做,而我
nikkypx