这个双冒号::是什么?例如Foo:酒吧。

我找到了一个定义:

::是一个一元操作符,允许在类或模块内定义的:常量、实例方法和类方法从类或模块外的任何地方访问。

如果你只能使用::来暴露任何东西,那么作用域(私有的,受保护的)有什么用呢?


当前回答

加上前面的答案,使用::访问实例方法是有效的Ruby。以下均有效:

MyClass::new::instance_method
MyClass::new.instance_method
MyClass.new::instance_method
MyClass.new.instance_method

根据最佳实践,我认为只推荐最后一种。

其他回答

不,它不是访问每个方法,它是一个“解析”操作符,也就是说,你用它来解析一个常量/静态符号的范围(或者你可以说的位置)。

例如,在第一行中,Rails使用它来查找ActiveRecord内部的基类。模块,在你的第二个模块中,它用于定位路由类的类方法(静态),等等。

它不是用来暴露任何东西,而是用来“定位”你瞄准镜周围的东西。

http://en.wikipedia.org/wiki/Scope_resolution_operator

module Amimal
      module Herbivorous
            EATER="plants" 
      end
end

Amimal::Herbivorous::EATER => "plants"

::用于创建作用域。为了从2个模块中访问Constant EATER,我们需要确定模块的范围以达到常数

简单来说,它是一个命名空间, 命名空间是模块、类、函数等的容器。同时也有助于解决名称冲突的问题。 在ruby中,你可以通过模块访问命名空间

module A
  class Article
     def Base
     end
  module B
  end
end

所以要访问类Article,我们使用A::Article。 在某些情况下你会看到 答::文章<应用程序::Base 这意味着模块A的Article类继承了Application模块的基类。

Ruby on rails使用::进行名称空间解析。

class User < ActiveRecord::Base

  VIDEOS_COUNT = 10
  Languages = { "English" => "en", "Spanish" => "es", "Mandarin Chinese" => "cn"}

end

使用它:

User::VIDEOS_COUNT
User::Languages
User::Languages.values_at("Spanish") => "en"

另外,其他用法是:当使用嵌套路由时

OmniauthCallbacksController在用户下定义。

并路由为:

devise_for :users, controllers: {omniauth_callbacks: "users/omniauth_callbacks"}


class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController

end

下面这个简单的例子说明了这一点:

MR_COUNT = 0        # constant defined on main Object class
module Foo
  MR_COUNT = 0
  ::MR_COUNT = 1    # set global count to 1
  MR_COUNT = 2      # set local count to 2
end

puts MR_COUNT       # this is the global constant: 1
puts Foo::MR_COUNT  # this is the local constant: 2

摘自http://www.tutorialspoint.com/ruby/ruby_operators.htm