我有机会在 StackOverflow 中环顾四周,发现了同样的问题,我试图从 Ruby Koans 中更好地理解这个问题(Ruby Koans:类定义上的显式作用域第 2 部分)。
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?
根据链接中的解释,其他人(包括我自己)的主要困惑似乎是因为类定义:
class MyAnimals::Oyster < Animal
# stuff goes in here
end
我最初的想法是 MyAnimals::Oyster 意味着 Oyster 类是在 MyAnimals 中定义的。换句话说,我认为上面的代码类似于下面的代码:
class MyAnimals
class Oyster < Animal
# stuff goes in here
end
end
为了测试我的想法,我在 IRB 中做了以下操作:
class MyAnimals
LEGS = 2
class Bird < Animal
def legs_in_bird
LEGS
end
end
end
class MyAnimals::Oyster # You should notice that I'm not inheriting from Animal anymore
def legs_in_oyster
LEGS
end
end
如果我的推理是正确的,那么我希望下面的代码返回 2
MyAnimals::Oyster.new.legs_in_oyster # => NameError: uninitialized constant MyAnimals::Oyster::LEGS
由于这不返回 2,有人可以向我解释为什么它不返回 2?
编辑:我忽略了添加 Animal 类;这里是:
class Animal
LEGS = 4
def legs_in_animal
LEGS
end
class NestedAnimal
def legs_in_nested_animal
LEGS
end
end
end