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

标签 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:: ?

最佳答案

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

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

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

相关文章:

java - 如何编写 Java 调试器命令行工具 (jdb) 的脚本?

ruby - 如何安全地读取 PKCS12 并将其传递给 ruby​​ 中的对象?

输入类型中的 PhP 命名空间

c++ - 来自通用命名空间的前向声明类(在 std::hash 中

c# - C#中命名空间的使用

mysql - Require 'mysql' 在 Textmate ruby​​ 脚本中失败,但在终端的 irb 中工作

ruby-on-rails - rails,在设置新对象时传入参数

c# - App.xaml 尝试在 Windows Phone 8 项目中使用 MVVM Light 时出错

ruby-on-rails - 如何向现有 Controller 添加新操作?

xml - 使用 XSL 删除所有 XML namespace ,但只有一个