2014-02-19 64 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