Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between String and ::String?

Tags:

ruby

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

like image 892
Pisto Avatar asked Jun 14 '26 18:06

Pisto


1 Answers

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

like image 93
xinit Avatar answered Jun 17 '26 23:06

xinit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!