双冒号在模块内部做什么?

Use*_*159 3 ruby module

我正在看下面的代码:

module Tag

  def sync_taggings_counter
    ::Tag.find_each do |t|
       # block here
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

而我::Tag对标签模块内部感到困惑.

我知道双冒号用于命名空间类和类/模块中的模块.但我从来没有见过它像上面那样使用过.这究竟是什么意思?

Nie*_* B. 8

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

例如

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
Run Code Online (Sandbox Code Playgroud)

如果Ruby无法在本地模块中找到引用的常量,那么前导通常不是必需的,因为Ruby会自动查找全局命名空间.所以,如果没有Bar的富模块中存在,然后Bar.greet::Bar.greet会做同样的事情.