2014-02-19 131 views
1

假设约常量变量一个简单的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!我想知道为什么?

+0

为什么投我失望!请站出来。 – dj199008

回答

2

这是因为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 
4

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 
+0

+为简单起见=) – Abdo

+0

我猜想当类“Const”被初始化时,“CONST = OUTER_CONST + 1”没有被执行。所以,我想知道红宝石如何识别CONST定义?这是我的问题。 – dj199008

+2

@ user2886717当然,但请注意,'def get_const ... end'定义了一个方法,**不执行其内容**;你在调用它的时候执行它的内容(在'Const.new.get_const'行),所以当'CONST'已经被定义时 – mdesantis