Ruby中名称空间的不同方式
我知道ruby中的两种名称空间方式:Ruby中名称空间的不同方式,ruby,namespaces,Ruby,Namespaces,我知道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 hun
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
为什么猫::MountainLion.new.hunt不起作用?命名空间是否声明为
模块
与声明为类的前缀的命名空间不同:?这两种方式在常量查找中不同。前者在Cat
名称空间中查找Lion
常量,这是正确的。后者在全局名称空间中查找::Lion
,这显然是不正确的,因为您没有这样的常量
有关此主题的更多信息,请访问此页面:
前者在
Cat::Cheetah
中查找Lion
,然后在Cat
中查找,最后在顶层查找。而后者在Cat::MountainLion
中查找,然后在顶层查找,因此跳过Cat
。