ruby - 使用::或模块声明类有什么区别?

标签 ruby

module Api
  module V1
    class ABC
    end
  end
end


class Api::V1::ABC
end

这些声明类有什么不同吗?

有什么优缺点吗?

最佳答案

是的,在您执行 constant lookups 时会有所不同. Module::nesting在这里会为您解决问题提供帮助。

module Api
  module V1
    class ABC
      p Module.nesting
    end
  end
end

# >> [Api::V1::ABC, Api::V1, Api]

module Api
  module V1
  end
end


class Api::V1::ABC
  p Module.nesting
end
# >> [Api::V1::ABC]

Module.nesting 返回在 Ruby 遍历 class/module 层次结构以查找常量之前搜索的词法封闭类/模块。

意思是,用下面的代码:

module Api
  module V1
    X = 12
  end
end

X = 10
class Api::V1::ABC
  p X
end
Api::V1::ABC.superclass # => Object
# >> 10

当常量查找时,它会首先搜索Module.nesting给出的常量数组,如果没有找到,直到祖先链/包含的模块。这意味着遵循 Api::V1::ABC.ancestors 输出。

现在在上面的示例中,您可以看到打印了 X 的值,它是在 Object 中定义的,而不是在 API::V1< 中。原因我上面说了。

现在来看下面的另一个例子:-

X = 10
module Api
  module V1
    X = 12
    class ABC
      p X
    end
  end
end

# >> 12

这里的常量查找将遵循数组 [Api::V1::ABC, Api::V1, Api]。您可以看到输出为 12,因为 Api::V1 中定义了常量 X

因此我们可以说 - 是的,这两个声明之间存在差异

关于ruby - 使用::或模块声明类有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23298437/

相关文章:

ruby - 给定任意长度的 "key path",如何设置 Ruby 哈希?

ruby - 更改 ruby​​ sprintf 中参数的顺序

ruby-on-rails - Rails - 强大的参数从嵌套属性中删除空字段

jquery - 选项卡不会更改为 “active” - jQuery 和 rails 3

ruby - 其他部分不适用于 Rails ajax 形式

ruby-on-rails - unicorn 和 unicorn_rails 有什么区别?

java - 从 Java 计算的 HMAC 值与 Ruby 代码不匹配

Ruby 条件语句

ruby-on-rails - Rails 上的 Ruby/设计 : Determining in model if user is logged in

Ruby 1.8.6 `gem install` 段错误与 "abort trap 6"