1

what's the difference between class ClassName and class ::ClassName in ruby?

class ClassName
end 

vs

class ::ClassName
end
user3828398
  • 495
  • 3
  • 9
  • 18
  • The [second answer to that question](http://stackoverflow.com/a/5318496/1318694) explains the root name space – Matt Jul 29 '14 at 08:14

2 Answers2

4

Your two examples would make difference if the classes were defined inside a ruby module, so:

module Foo
  class ClassName
  end 
end

would define a new class inside the Foo module. This could be accessed like Foo::ClassName.

On the other hand, this:

module Foo
  class ::ClassName
  end 
end

would define (or monkey-patch) the class ClassName in the root namespace.

Matouš Borák
  • 15,606
  • 1
  • 42
  • 53
1

::Class says 'look for Class in top level namespace'. The difference shows when in context of a module.

module A
  def foo
    X.new
  end
end

A.foo # => A::X.new

module B
  def foo
    ::X.new
  end
end

B.foo # => X.new
Toms Mikoss
  • 9,097
  • 10
  • 29
  • 41