【发布时间】:2016-06-15 22:15:02
【问题描述】:
我正在做一个项目,但遇到了一个我不熟悉的错误。当我运行我的代码时,我收到'undefined method `-' for nil:NilClass (NoMethodError)',经过一些研究,这意味着 target_floors[j] 为 nil。为什么会发生这种情况以及如何解决?
def retrieve_floor(n, target_floors)
smallestDifference = n
toReturn = 0
for i in 1..n
tempDiff = 0
for j in 0..target_floors.length
difference = target_floors[j] - i
if difference > 0
tempDiff += difference
else
tempDiff += difference.abs
end
end
if tempDiff < smallestDifference
smallestDifference = tempDiff
toReturn = i
end
end
return toReturn
end
【问题讨论】:
-
由于
target_floors被传递给此方法,因此传递它的人提供了数组中的nil值。你想怎么解决?是否期望数组的某些元素是nil?如果不是,那么调用者有错。如果是,那么您只需要检查nil(if target_floors[j].nil? ...)。 -
更有可能
j大于数组的最后一个索引。
标签: ruby