假设约常量变量一个简单的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
的结果应该是零,但结果是100!我想知道为什么?
假设约常量变量一个简单的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
的结果应该是零,但结果是100!我想知道为什么?
这是因为Ruby是dynamic和常量查找发生在运行时。另外请记住,您的脚本是按顺序评估的(即逐行)。
我添加了一些意见为清楚:
OUTER_CONST = 99
class Const
def get_const
CONST
end
CONST = OUTER_CONST + 1
# the CONST constant is now
# defined and has the value 100
end
# at this point the Const class
# and CONST constant are defined and can be used
# here you are calling the `get_const` method
# which asks for the value of `CONST` so the
# constant lookup procedure will now start and
# will correctly pick up the current value of `CONST`
Const.new.get_const # => 100
get_const
是一种方法,你在之后调用它CONST
定义;所以当你叫它CONST
已经定义。
def get_const ... end
定义了一种方法,不执行其内容;您在Const.new.get_const
行呼叫时执行其内容,因此当CONST
已被定义。
除了:如果CONST
没有在get_const
电话的那一刻定义的,你不会得到nil
,但NameError
:
class Const
def get_const
CONST
end
end
Const.new.get_const #=> NameError: uninitialized constant Const::CONST
为什么投我失望!请站出来。 – dj199008