2011-03-28 5 views
19

이 원본의 내용을 명확히하고 싶습니다. post. 대답은 루비가이 순서에 상수 정의를 검색 제안 :Ruby Koans : 클래스 정의 부분의 명시적인 범위 지정 2

  • 모든 외부 범위가 바깥 쪽 범위
  • 포함 모듈
  • 슈퍼 클래스 (들)
  • 을 (최상위 때까지 반복에 도달)
    1. 커널

    그래서 명확하게

  • 개체에서 어느 단계 (1-6)는 에 대해 상수 LEGS에 대한 값입니까? 수퍼 클래스 Animal에서 왔습니까? 둘러싸는 범위로 간주되지 않으므로 클래스 MyAnimals의 범위가 무시됩니까? 이것은 명시적인 MyAnimals::Oyster 클래스 정의 때문입니까?

    감사합니다. 이해하려고 애를 써. 코드는 다음과 같습니다.

    class Animal 
        LEGS = 4 
        def legs_in_animal 
        LEGS 
        end 
    
        class NestedAnimal 
        def legs_in_nested_animal 
         LEGS 
        end 
        end 
    end 
    
    def test_nested_classes_inherit_constants_from_enclosing_classes 
        assert_equal 4, Animal::NestedAnimal.new.legs_in_nested_animal 
    end 
    
    # ------------------------------------------------------------------ 
    
    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 heirarachy? 
    
    # ------------------------------------------------------------------ 
    
    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 heirarachy? Why is it 
    # different than the previous answer? 
    end 
    
  • +0

    :

    참고로, 나는 (당신이 링크 된 질문에서 참조로)는 다음 URL에서이 통찰력을 가지고/questions/4627735/ruby-explicit-scope-on-a-class 정의 –

    +0

    @Andrew - 게시물에 명시했습니다. 나는 이해하지 못했던 부분이 있기 때문에 주제에 대한 더 많은 토론을하려고 노력하고 있습니다. 나는 단지 거기에 코멘트해야합니까? –

    +0

    미안하지만, 나는 그것을 알아 차리지 못했다. –

    답변

    31

    나는 아주 똑같은 질문을 생각하고있었습니다. 나는 범위를 정할 때 전문가가 아니지만, 다음의 간단한 설명이 제게 많은 의미가 있습니다. 아마도 도움이 될 것입니다. 루비는 당신이 실제로 MyAnimals의 범위에있는 적이 있기 때문에 MyAnimals 2로 설정 LEGS 값에 대한 지식 (약간 어긋)가되지 않도록

    MyAnimals::Oyster을 정의

    당신은, 전역 범위에 여전히.

    class MyAnimals 
        class Oyster < Animal 
        def legs_in_oyster 
         LEGS # => 2 
        end 
        end 
    end 
    

    의 차이는 위의 코드에서, 당신은 Oyster를 정의하는 시간, 당신은 MyAnimals의 범위에 떨어 뜨린 것입니다 : 당신이 Oyster이 방법을 정의한다면

    그러나, 상황이 다른 것 , 그래서 루비는 LEGSMyAnimals::LEGS (2)이고 Animal::LEGS (4)가 아니라는 것을 안다. http://stackoverflow.com : 누군가가 전에이 간화선에 대해 질문 있어요

    +0

    감사합니다. @bowsersenior! 나는 그 링크를 보았지만 충분히 멀리 읽지는 않았다. 사용자 오류. –

    +0

    나는 그것이 굴 '동물'이어야한다고 생각한다 –

    +0

    감사합니다 @ AndreyBotalov! 수정하기 위해 코드를 업데이트했습니다. – bowsersenior