I know :: allows us to access items in modules, or class-level items in classes, but what does only ::String mean??
What is the difference between String =="hi".class and ::String=="hi".class??
The class is defined as below.
class String
end
::String references the top level String class. String references either a string in the current namespace or namespaces above.
Take a look at the following code:
module MyModule
class String
def initialize(s); end
def split(operator=nil)
puts "This string doesn't split"
end
end
class SomeClass
def bar
s = String.new("foo:bar")
s.split(":")
end
def foo
s = ::String.new("foo:bar")
s.split(":")
end
end
end
sc = MyModule::SomeClass.new
sc.foo
=> ["foo", "bar"]
sc.bar
This string doesn't split
=> nil
Since String exists in both the top level namespace and in the module MyModule, you need to explicitly reference the top level string by using the top level namespace ::.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With