【问题标题】:Ruby: undefined local variable (NameError) -- but it is definedRuby:未定义的局部变量(NameError)——但它已定义
【发布时间】:2015-12-24 19:24:33
【问题描述】:

这是我的 Naughts and Crosses (tic-tac-toe) 游戏代码的一部分。

positions = [" ", " ", " ", " ", " ", " ", " ", " ", " "]

# Returns .. 1 = Square already owned, 2 = Blank square, 0 = Enemy square
def check_square(side, square)
  if positions[square] == side
    state = 1
  elsif positions[square] == B
    state = 2
  else
    state = 0
  end
  return state
end

当我运行程序时出现错误:

在 `check_square' 中:未定义的局部变量或方法 `positions' 用于 main:Object (NameError)

但是它实际上是在它上面定义的。我已经在自己的 .rb 中运行了代码的 sn-p 并且它工作正常,所以我不明白为什么它不起作用。我必须假设它与职位的范围有关,但至少对我来说(初学者程序员),我不明白为什么它在这里不起作用,但在它自己的程序中起作用。

非常感谢任何帮助。

【问题讨论】:

    标签: ruby variables nameerror


    【解决方案1】:

    局部变量的范围不能跨越方法定义。在方法定义之外分配的positions 在方法定义中不可见。

    要使其可见,例如,您可以将其设为实例变量、类变量、全局变量或常量。或者,您可以将其作为参数传递给方法。

    【讨论】:

    • 谢谢,我已经将它设置为一个全局变量,现在它似乎可以工作了!
    • 但是,在面向对象编程中不推荐使用全局变量。
    • 你会推荐我用什么来代替?
    • 实例变量或常量
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-29
    • 2013-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-22
    相关资源
    最近更新 更多