What is Ruby's double-colon `::`?

后端 未结 10 1981
南笙
南笙 2020-11-22 10:09

What is this double-colon ::? E.g. Foo::Bar.

I found a definition:

The :: is a unary operator that all

10条回答
  •  清酒与你
    2020-11-22 10:37

    :: Lets you access a constant, module, or class defined inside another class or module. It is used to provide namespaces so that method and class names don't conflict with other classes by different authors.

    When you see ActiveRecord::Base in Rails it means that Rails has something like

    module ActiveRecord
      class Base
      end
    end
    

    i.e. a class called Base inside a module ActiveRecord which is then referenced as ActiveRecord::Base (you can find this in the Rails source in activerecord-n.n.n/lib/active_record/base.rb)

    A common use of :: is to access constants defined in modules e.g.

    module Math
      PI = 3.141 # ...
    end
    
    puts Math::PI
    

    The :: operator does not allow you to bypass visibility of methods marked private or protected.

提交回复
热议问题