【问题标题】:Ruby undefined method `-' for nil:NilClass (NoMethodError)Ruby 未定义方法 `-' 用于 nil:NilClass (NoMethodError)
【发布时间】: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


【解决方案1】:

first..last 形式的范围包括端点,因此您将迭代一个超出数组末尾的范围。

您可以改用0...target_floors.length(包括0,但不包括结尾),但更好、更红的方法是使用each 来迭代数组,而不是使用索引。

【讨论】:

    猜你喜欢
    • 2013-02-17
    • 2014-03-16
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多