Guichi Ren Guichi Ren - 2 years ago 98
Ruby Question

Purpose of :: before include module in ruby

What is the different between the following two include statements:

include ::Module1:Module2


include Module1::Module2

Both worked in my case. But, I just wonder which one is better (or both are totally fine).

Answer Source

Calling ::Module1::Module2 would be referencing the top-level namespace, rather than the relative namespace of where the statement is being executed.

This is useful in scenarios where you're trying to reference a top-level module within another module, like so:

class YourClass

module YourModule
  class YourClass

  def self.new_outer_class

  def self.new_inner_class

With the above setup, calling #new_outer_class would actually instantiate the instance of YourClass class defined outside of YourModule, whereas calling #new_inner_class would instantiate YourModule::YourClass since it's relative to and called within YourModule.

Hope that helps!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download