我想澄清這個原始的post的一些東西。的回答表明紅寶石的順序搜索所述常數定義:Ruby Koans:在類定義第2部分的顯式範圍
- 封閉範圍
- 任何外部範圍(重複,直到頂層到達)
- 包括模塊
- 超類(ES)
- 對象
- 內核
所以要澄清,在步驟(1-6)是否爲legs_in_oyster
找到的常量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
有人來問這個公案前:http://stackoverflow.com/questions/4627735/ruby -express -scope-on-a-class-definition – 2011-03-28 22:21:16
@Andrew - 我在帖子中指定。我只是想就這個話題進行更多的討論,因爲有些部分我不明白。我應該在那裏發表評論嗎? – 2011-03-29 01:29:48
對不起,我沒有注意到。 – 2011-03-29 01:32:44