2012-12-01 3 views
4

rubykoans 튜토리얼에서 코드 스 니펫을 보여 드리겠습니다. 다음 코드를 살펴 보자 : (가) 굵게 의도하지만 (나는 asteriks으로 강조) 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**? 

는 사실 문제는 의견이다. 누가 제발 설명해 주실 래요? 미리 감사드립니다!

답변

18

여기에 답변 해 드리겠습니다 : Ruby: explicit scoping on a class definition. 그러나 아마 그것은 분명하지 않습니다. 링크 된 기사를 읽으면 대답에 도움이 될 것입니다.

기본적으로 BirdMyAnimals의 범위에서 선언되며 상수를 확인할 때 더 높은 우선 순위를 갖습니다. OysterMyAnimals 네임 스페이스에 있지만 해당 범위에서 선언되지 않았습니다.

각 클래스에 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]

이 차이를 볼 수 있습니까?