2011-03-28 64 views
19

我想澄清這個原始的post的一些東西。的回答表明紅寶石的順序搜索所述常數定義:Ruby Koans:在類定義第2部分的顯式範圍

  1. 封閉範圍
  2. 任何外部範圍(重複,直到頂層到達)
  3. 包括模塊
  4. 超類(ES)
  5. 對象
  6. 內核

所以要澄清,在步驟(1-6)是否爲legs_in_oyster找到的常量LEGS的值?它是否來自超類AnimalMyAnimals的範圍是否被忽略,因爲它不被視爲封閉範圍?這是由於明確的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

有人來問這個公案前:http://stackoverflow.com/questions/4627735/ruby​​ -express -scope-on-a-class-definition – 2011-03-28 22:21:16

+0

@Andrew - 我在帖子中指定。我只是想就這個話題進行更多的討論,因爲有些部分我不明白。我應該在那裏發表評論嗎? – 2011-03-29 01:29:48

+0

對不起,我沒有注意到。 – 2011-03-29 01:32:44

回答

31

我只是在思考同一個問題,從同一個公司。我不是專家的範圍,但下面的簡單解釋對我來說很有意義,也許它也會對你有所幫助。

當你定義MyAnimals::Oyster你仍然在全球範圍內,使紅寶石沒有設置爲2 MyAnimals因爲你從來沒有真正在的MyAnimals範圍的LEGS值的知識(有點違反直覺)。

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

不同的是,在上面的代碼,由您定義Oyster的時候,你已經投進MyAnimals範圍:

但是,如果你定義Oyster這樣的事情會有所不同,所以紅寶石知道LEGS是指MyAnimals::LEGS(2)而不是Animal::LEGS(4)。

僅供參考,我得到這個見解從以下URL(在這個問題引用鏈接到您):

+0

謝謝@bowsersenior!我看到了這一聯繫,但沒有讀得太多。用戶錯誤。 – 2011-03-30 13:17:25

+0

我認爲它應該是'Oyster 2012-12-20 12:25:28

+0

謝謝@AndreyBotalov!更新了代碼以糾正它。 – bowsersenior 2012-12-21 00:30:09