Ruby中不同的命名空间方式

时间:2018-06-20 07:57:46

标签: ruby namespaces

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::的前缀的命名空间?

1 个答案:

答案 0 :(得分:1)

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

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