0

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).

Guichi Ren
  • 67
  • 1
  • 5

1 Answers1

1

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!

Zoran
  • 4,196
  • 2
  • 22
  • 33
  • Does that mean in my case both are interchangeable? – Guichi Ren Apr 26 '16 at 23:24
  • In your specific case, they would be effectively achieving the same result. However, using `::Module1::Module2` would break the moment another namespace level is added on top of `Module1`. – Zoran Apr 26 '16 at 23:41