gpt4 book ai didi

Ruby:类定义的显式范围

转载 作者:数据小太阳 更新时间:2023-10-29 06:31:01 24 4
gpt4 key购买 nike

免责声明:代码取自 ruby koans

这是对类内常量作用域的讨论。下面是几个类的定义:

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

此时执行 MyAnimals::Bird.new.legs_in_bird 结果为 2,我明白为什么——在继承层次结构之前搜索常量的词法空间。

然后定义这个类:

class MyAnimals::Oyster < Animal
def legs_in_oyster
LEGS
end
end

教程说现在调用 MyAnimals::Oyster.new.legs_in_oyster 结果是 4,我无法弄清楚。在我看来,Oyster 是 MyAnimals 中的一个嵌套类,因此我希望它的行为方式与上面的 Birds 类相同。我遗漏了一些关于用显式范围定义方式声明 Oyster 类的关键信息。

谁能给我解释一下?我通过 Google 找到了数百个 ruby​​ 类教程,但没有一个解决这种情况。

提前谢谢你...

最佳答案

我认为this example最好的解释。 Ruby 按以下顺序搜索常量定义:

  1. 封闭范围
  2. 任何外部范围(重复直到达到顶层) 任何外部范围(直到但不包括顶层
  3. 包含的模块
  4. 父类(super class)
  5. 顶级
  6. 对象
  7. 内核

编辑

感谢Mark Amery指出这个错误。只有在没有封闭范围和/或父类(super class)的情况下才能达到顶层。链接示例实际上清楚地说明了这一点,遗憾的是我读错了。

这种情况的一个例子:

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:类定义的显式范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4627735/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com