Ad

What's Difference In ::ModuleName::ClassName And ModuleName::ClassName

- 1 answer

In ruby, I'm starting to see a pretty normal practice including modules and mixins referenced as ::ModuleName::ClassName, where in the past it was pretty much just ModuleName::ClassName.

What I'd like to get here is a decent understanding of why this practice is being seen more lately and what it does differently.

What's the difference?

What's the benefit (if the prior doesn't answer this)?

Thanks in advance for your input.

Ad

Answer

If you put the :: in the beginning you are referring to the global namespace, if you don't you are referring to your current namespace.

Usually if you don't have a class/module with the same name inside your class/module you would not need to use the :: in the beginning.

class Customer

  def to_s
    "Customer global"
  end

end


class Order

  class Customer
    def to_s
      "Customer within order"
    end
  end


  def initialize
    puts Customer.new
    puts ::Customer.new
  end


end

Order.new

will print out

Customer within order
Customer global
Ad
source: stackoverflow.com
Ad