假设一个关于 CONSTANT 变量的简单 ruby 程序:
OUTER_CONST = 99
class Const
def get_const
CONST
end
CONST = OUTER_CONST + 1
end
puts Const.new.get_const
我假设 Const.new.get_const
的结果应该是 nil,但结果是 100!我想知道为什么?
最佳答案
get_const
是一种方法,您在 CONST
定义之后调用它;所以当你调用它时 CONST
已经被定义了。
def get_const ... end
定义一个方法,不执行其内容;当您在 Const.new.get_const
行调用它时执行它的内容,所以当 CONST
已经定义时。
此外:如果在调用get_const
时未定义CONST
,您将不会得到nil
,而是一个 NameError
:
class Const
def get_const
CONST
end
end
Const.new.get_const #=> NameError: uninitialized constant Const::CONST
关于ruby - 对 ruby CONSTANT 的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21883173/