我将向您展示rubykoans教程中的代码片段。考虑下一个代码:
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**?
实际上问题在评论中(我用星号突出显示(尽管它打算用粗体显示))。有人可以解释一下吗?提前致谢!