2012-12-01 66 views
4

我將從rubykoans教程中顯示您的代碼片段。考慮下面的代碼:Ruby示波器,常量優先級:詞法作用域或繼承樹

class MyAnimals 
LEGS = 2 

    class Bird < Animal 
    def legs_in_bird 
     LEGS 
    end 
    end 
end 

def test_who_wins_with_both_nested_and_inherited_constants 
    assert_equal 2, MyAnimals::Bird.new.legs_in_bird 
end 

# QUESTION: Which has precedence: The constant in the lexical scope, 
# or the constant from the inheritance hierarchy? 
# ------------------------------------------------------------------ 

class MyAnimals::Oyster < Animal 
    def legs_in_oyster 
    LEGS 
    end 
end 

def test_who_wins_with_explicit_scoping_on_class_definition 
    assert_equal 4, MyAnimals::Oyster.new.legs_in_oyster 
end 

# QUESTION: Now which has precedence: The constant in the lexical 
# scope, or the constant from the inheritance hierarchy? Why is it 
# **different than the previous answer**? 

其實這個問題是在評論(我asteriks強​​調它(儘管它旨在以粗體))。請有人解釋我嗎?提前致謝!

回答

18

這裏回答了這裏:Ruby: explicit scoping on a class definition。但也許它不是很清楚。如果您閱讀鏈接的文章,它將幫助您解答問題。

基本上,Bird是在MyAnimals的範圍內聲明的,它在解析常量時具有更高的優先級。 Oyster位於MyAnimals名稱空間中,但未在該範圍內聲明。

p Module.nesting插入每個類中,向您展示封閉範圍是什麼。

class MyAnimals 
    LEGS = 2 

    class Bird < Animal 

    p Module.nesting 
    def legs_in_bird 
     LEGS 
    end 
    end 
end 

產量:[AboutConstants::MyAnimals::Bird, AboutConstants::MyAnimals, AboutConstants]

而且

class MyAnimals::Oyster < Animal 
    p Module.nesting 

    def legs_in_oyster 
    LEGS 
    end 
end 

產量:[AboutConstants::MyAnimals::Oyster, AboutConstants]

看到區別?