【问题标题】:What does a double colon do inside a module? [duplicate]双冒号在模块内有什么作用? [复制]
【发布时间】:2013-11-22 17:23:40
【问题描述】:

我正在查看以下代码:

module Tag

  def sync_taggings_counter
    ::Tag.find_each do |t|
       # block here
    end
  end
end

我对 Tag 模块中的 ::Tag 感到困惑。

我知道双冒号用于在类/模块中命名空间类和模块。但我从未见过像上面那样使用它。具体是什么意思?

【问题讨论】:

标签: ruby module


【解决方案1】:

它是一个范围修饰符。使用双冒号作为常量 (Tag) 的前缀可确保您查看的是根/全局命名空间,而不是当前模块。

例如

module Foo
  class Bar
    def self.greet
      "Hello from the Foo::Bar class"
    end
  end

  class Baz
    def self.scope_test
      Bar.greet # Resolves to the Bar class within the Foo module.
      ::Bar.greet # Resolves to the global Bar class.
    end
  end
end

class Bar
  def self.greet
    "Hello from the Bar class"
  end
end

如果在本地模块中找不到引用的常量,Ruby 会自动在全局命名空间中查找,因此前置通常是不必要的。因此,如果 Foo 模块中不存在 Bar,那么 Bar.greet::Bar.greet 将执行完全相同的操作。

【讨论】:

    猜你喜欢
    • 2010-12-03
    • 1970-01-01
    • 2021-12-22
    • 2011-01-17
    • 2016-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多