gpt4 book ai didi

ruby - Ruby 中命名空间的不同方式

转载 作者:行者123 更新时间:2023-12-04 17:01:49 32 4
gpt4 key购买 nike

AFAIK 我知道这两种在 ruby​​ 中命名空间的方法:

module Cat
class Lion
def hunt
p 'roaming for prey ...'
end
end

class Cheetah
def hunt
Lion.new.hunt
p 'Oops there is a lion. Hide first ...'
end
end
end

class Cat::MountainLion
def hunt
Lion.new.hunt
p 'roaming for prey ... (since I dont live in the same continent as lion)'
end
end

Cat::Cheetah.new.hunt
Cat::MountainLion.new.hunt

为什么是 Cat::MountainLion.new.hunt不起作用?命名空间是否声明为 module不同于声明为类前缀的那些 class Cat:: ?

最佳答案

这两种方式在不断查找上有所不同。前者找Lion常数在 Cat命名空间,这是正确的。后者寻找::Lion , 在全局命名空间中,这显然是不正确的,因为您没有这样的常量。

有关此主题的更多信息,请访问此页面:
https://cirw.in/blog/constant-lookup.html

关于ruby - Ruby 中命名空间的不同方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50943140/

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