What does :: mean Ruby syntax?

What is :: ?

 @song ||= ::TwelveDaysSong.new 
+5
source share
3 answers

Ruby :: (Double Half Columns)

Top-level constants are referenced by double colons

 class TwelveDaysSong end a = TwelveDaysSong.new #I could wrote it like this too a = ::TwelveDaysSong.new module Twelve class TwelveDaysSongs end end b = Twelve::TwelveDaysSong.new #b is not equal to a = ::TwelveDaysSong.new #neither a = TwelveDaysSong.new 

Classes are also constants, so if you have a constant

 HELLOWOLRD = 'hw' 

you can call it like this: ::HELLOWORLD

+7
source

This is a method of lazily initializing an @song instance @song .

If @song already set (some plausible value, i.e. not nil or false ), then the expression just evaluates that value.

If, however, @song is not already set for that value, then it creates a new instance of the TwelveDaysSong class and assigns it to @song . Then, as before, the expression evaluates the @song value, but this value is now a reference to the newly created TwelveDaysSong object.

Using :: in a class name means that it is an absolute top-level class; it will use the top-level class even if there is a TwelveDaysSong class defined in any current module.

+1
source

Return @song

If @song is false (for example, it does not exist)
create a new instance of the object ::TwelveDaysSong as @song

0
source

Source: https://habr.com/ru/post/1202514/


All Articles