我想澄清这个原始的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