Ruby:对类定义的显式范围 [英] Ruby: explicit scoping on a class definition
问题描述
免责声明:取自 ruby koans 的代码
这是来自类中的常量范围。这里是几个类的定义:
This is from a discussion of constants scoping within classes. Here is the defintion of a couple few classes:
class Animal
LEGS = 4
def legs_in_animal
LEGS
end
end
class MyAnimals
LEGS = 2
class Bird < Animal
def legs_in_bird
LEGS
end
end
end
b $ b
在这一点上, MyAnimals :: Bird.new.legs_in_bird
结果为2,我理解为什么 - 在继承层次之前搜索常量的词法空间
At this point doing MyAnimals::Bird.new.legs_in_bird
results in 2 and I understand why--search lexical space for the constant before the inheritance heirarchy.
然后这个类被定义:
class MyAnimals::Oyster < Animal
def legs_in_oyster
LEGS
end
end
教程说,现在调用 MyAnimals :: Oyster.new.legs_in_oyster
导致4,我不能弄清楚。对我来说,Oyster是MyAnimals中的一个嵌套类,因此我期望它的行为方式与Birds类相同。我缺少一些关于什么声明类Oyster与显式范围的手段。一些关键信息。
The tutorial says that now calling MyAnimals::Oyster.new.legs_in_oyster
results in 4 and I can't figure it out. It appears to me that Oyster is a nested class in MyAnimals and as such I expected it to behave the same ways as the Birds class did above. I'm missing some key information about what declaring the class Oyster with explicit scoping means.
任何人都可以解释这个给我吗?我已经通过Google找到了数百个ruby类教程,但没有一个解决这种情况。
can anyone explain this to me? I've found hundreds of ruby class tutorials via Google but none of them address this situation.
提前谢谢...
推荐答案
我认为此示例最好地解释。 Ruby按此顺序搜索常量定义:
I think this example explains it best. Ruby searches for the constant definition in this order:
- 包围范围
- 顶层
- 包含的模块
- 超类
- 顶级
- 对象
- li>
- The enclosing scope
Any outer scopes (repeat until top level is reached)Any outer scopes (up to but not including the top level- Included modules
- Superclass(es)
- Top level
- Object
- Kernel
EDIT
感谢 Mark Amery 来指出这个错误。只有在没有封闭范围和/或超类的情况下才能达到顶层。
Thanks to Mark Amery for pointing out this error. The top-level is only reached in the case where there are no enclosing scopes and/or superclasses. The linked example actually makes this clear, sadly I read it wrong.
这种情况的一个例子:
FOO = 'I pity the foo!'
module One
FOO = 'one'
class Two
FOO = 'two'
def self.foo
FOO
end
end
class Three < Two
def self.foo
FOO
end
end
end
class Four
class Five < Four
def self.foo
FOO
end
end
end
describe FOO do
it "depends where it is defined" do
expect(FOO).to eq 'I pity the foo!' # top-level
expect(One::FOO).to eq 'one' # module
expect(One::Two.foo).to eq 'two' # class
expect(One::Three.foo).to eq 'one' # outer scope (One) comes before superclass
expect(Four::Five.foo).to eq 'I pity the foo!' # top-level
end
end
这篇关于Ruby:对类定义的显式范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!