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

我知道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

为什么猫::MountainLion.new.hunt不起作用?命名空间是否声明为
模块
与声明为类的前缀的命名空间不同:?

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

有关此主题的更多信息,请访问此页面:

前者在
Cat::Cheetah
中查找
Lion
,然后在
Cat
中查找,最后在顶层查找。而后者在
Cat::MountainLion
中查找,然后在顶层查找,因此跳过
Cat