Ruby: 未定义局部变量 (NameError) -- 但已定义
Ruby: undefined local variable (NameError) -- but it is defined
这是我的 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
当我 运行 程序时出现错误:
in `check_square': undefined local variable or method `positions' for main:Object (NameError)
然而,它的字面定义就在它的正上方。我在自己的 .rb 中有 运行 代码片段,它工作正常,所以我不明白为什么它不起作用。我必须假设它与职位范围有关,但至少对我(初级程序员)来说,我不明白为什么它在这里不起作用但在它自己的程序中起作用。
非常感谢任何帮助。
局部变量的范围不能跨越方法定义。 positions
在方法定义之外分配的内容在方法定义中不可见。
要使其可见,您可以将其设为实例变量、class变量、全局变量或常量等。或者,您可以将其作为参数传递给方法。
这是我的 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
当我 运行 程序时出现错误:
in `check_square': undefined local variable or method `positions' for main:Object (NameError)
然而,它的字面定义就在它的正上方。我在自己的 .rb 中有 运行 代码片段,它工作正常,所以我不明白为什么它不起作用。我必须假设它与职位范围有关,但至少对我(初级程序员)来说,我不明白为什么它在这里不起作用但在它自己的程序中起作用。
非常感谢任何帮助。
局部变量的范围不能跨越方法定义。 positions
在方法定义之外分配的内容在方法定义中不可见。
要使其可见,您可以将其设为实例变量、class变量、全局变量或常量等。或者,您可以将其作为参数传递给方法。