2012-12-21 21 views
3

有人可以檢查我的這種行爲,我注意到了嗎?Ruby:未定義的局部變量如果在不同的代碼路徑中定義,那麼確定嗎?

如果您不將任何內容分配給本地變量並嘗試將其打印出來,則會按預期生成異常。如果您在無法訪問的代碼路徑中分配本地變量,它將起作用。應該是這樣嗎?

def a 
    # Should generate an error because foobar is not defined. 
    puts foobar 
end 

def b 
    # This block never is run but foobar is entered into the symbol table. 
    if false 
    foobar = 123 
    end 

    # This succeeds in printing nil 
    puts foobar 
end 

begin; a; rescue Exception => e; puts "ERROR: #{e.message}"; end 
begin; b; rescue Exception => e; puts "ERROR: #{e.message}"; end 

回答

6

是的,這是正確的。 Ruby在解析過程中確定變量的範圍,而不是在函數的運行期間。因此,只需引用一個變量就足以定義它,即使它在不可訪問的代碼路徑中引用。

我碰到了這一段時間 - 看到this blog post的行爲寫作。

+1

在Ruby中,像foobar這樣的每個符號都可以是一個方法或一個變量,但假定它是一個方法,除非它被引用爲一個變量。在這種情況下,它被「定義」爲一個變量,但該變量沒有被定義爲任何特定的值。 – tadman

+0

謝謝,我也剛剛發現另一個StackOverflow問題:http://stackoverflow.com/questions/4154864/i-dont-understand-ruby-local-scope – Amy