我将向您展示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**?
实际上,问题是在评论中(我用星号突出显示了它(尽管它是粗体的)。有人能给我解释一下吗?提前谢谢!
最佳答案
这里回答:Ruby: explicit scoping on a class definition。但也许还不太清楚。如果你读了链接的文章,它会帮助你找到答案。
基本上,Bird
是在MyAnimals
的范围内声明的,这在解析常量时具有更高的优先级。Oyster
位于MyAnimals
命名空间中,但未在该作用域中声明。
将p Module.nesting
插入到每个类中,并显示封闭作用域是什么。
class MyAnimals
LEGS = 2
class Bird < Animal
p Module.nesting
def legs_in_bird
LEGS
end
end
end
收益率:
[AboutConstants::MyAnimals::Bird, AboutConstants::MyAnimals, AboutConstants]
和
class MyAnimals::Oyster < Animal
p Module.nesting
def legs_in_oyster
LEGS
end
end
收益率:
[AboutConstants::MyAnimals::Oyster, AboutConstants]
看到区别了吗?
关于ruby - Ruby作用域,常量优先级:词法作用域或继承树,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13661193/