I'm writing code in a namespace where the File module exists (inside another module)
And I need to access the ruby File class.
In php this could be done like this: \File
How to do that in ruby?
The namespace in Ruby is defined by prefixing the keyword module in front of the namespace name. The name of namespaces and classes always start from a capital letter. You can access the sub members of double with the help of :: operator. It is also called the constant resolution operator.
The :: is a unary operator that allows: constants, instance methods and class methods defined within a class or module, to be accessed from anywhere outside the class or module. Remember in Ruby, classes and methods may be considered constants too.
The method definitions look similar, too: Module methods are defined just like class methods. As with class methods, you call a module method by preceding its name with the module's name and a period, and you reference a constant using the module name and two colons.
You can define and access instance variables within a module's instance methods, but you can't actually instantiate a module.
::File
Prefixing with ::
accesses the 'root' of the namespace tree.
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