Accessing module methods with ::

后端 未结 2 929
無奈伤痛
無奈伤痛 2021-01-12 09:14

Documentation I\'ve read tells me to use Module.method to access methods in a module. However, I can use Module::method as well. Is this syntactic sugar, or am I confused?

2条回答
  •  既然无缘
    2021-01-12 10:13

    The :: is called scope resolution operator, which is used to find out under what scope the method, class or constant is defined.

    In the following example, we use :: to access class Base which is defined under module ActiveRecord

    ActiveRecord::Base.connection_config
    # => {:pool=>5, :timeout=>5000, :database=>"db/development.sqlite3", :adapter=>"sqlite3"}
    

    We use :: to access constants defined in module

    > Cat::FURRY_LEVEL
    => 4
    > Cat.FURRY_LEVEL
    => undefined method `FURRY_LEVEL' for Cat:Module (NoMethodError)
    

    The . operator is used to call a module method(defined with self.) of a module.

    Summary: Even though both :: and . does the same job here, it is used for different purpose. You can read more from here.

提交回复
热议问题