4
我將從rubykoans教程中顯示您的代碼片段。考慮下面的代碼:Ruby示波器,常量優先級:詞法作用域或繼承樹
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**?
其實這個問題是在評論(我asteriks強調它(儘管它旨在以粗體))。請有人解釋我嗎?提前致謝!