Guichi Ren Guichi Ren - 7 months ago 26
Ruby Question

Purpose of :: before include module in ruby

What is the different between the following two include statements:

include ::Module1:Module2


and

include Module1::Module2


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

Answer

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
end

module YourModule
  class YourClass
  end

  def self.new_outer_class
    ::YourClass.new
  end

  def self.new_inner_class
    YourClass.new
  end
end

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!

Comments