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/