我想澄清这篇原帖的一些内容.答案表明Ruby按此顺序搜索常量定义:
那么澄清一下,在哪一步(1-6)是LEGS找到的常数的值legs_in_oyster?它来自超类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
Run Code Online (Sandbox Code Playgroud)
bow*_*ior 32
我只是在同一个公案中思考同样的问题.我不是范围界定的专家,但以下简单的解释对我来说很有意义,也许它对你也有帮助.
当你定义MyAnimals::Oyster你仍然在全局范围内时,所以ruby不知道LEGS设置为2 的值,MyAnimals因为你实际上并不属于MyAnimals(有点违反直觉)的范围.
但是,如果要以Oyster这种方式定义,情况会有所不同:
class MyAnimals
class Oyster < Animal
def legs_in_oyster
LEGS # => 2
end
end
end
Run Code Online (Sandbox Code Playgroud)
不同之处在于,在上面的代码中,在您定义的时候Oyster,您已经进入了范围MyAnimals,因此ruby知道LEGS引用MyAnimals::LEGS(2)而不是Animal::LEGS(4).
仅供参考,我从以下网址获得了这一见解(在您链接的问题中引用):