What is ::
?
@song ||= ::TwelveDaysSong.new
Use :: for describing class methods, # for describing instance methods, and use . for example code.
:: Lets you access a constant, module, or class defined inside another class or module.
Double colon ( : ) operator is use to access the constants, class methods and instance methods defined within a class or module to anywhere outside the class or module.
What is symbol. Ruby symbols are created by placing a colon (:) before a word. You can think of it as an immutable string. A symbol is an instance of Symbol class, and for any given name of symbol there is only one Symbol object.
This is a method of lazily initializing the @song
instance variable.
If @song
is already set (to some truthy value, that is, not nil
or false
), then the expression just evaluates to that value.
If, however, @song
is not already set to such a value, then it creates a new instance of the class TwelveDaysSong
and assigns it to @song
. Then, as before, the expression evaluates to the value of @song
, but that value is now a reference to the newly-created TwelveDaysSong
object.
The use of ::
on the class name means that it is an absolute, top-level class; it will use the top-level class even if there is also a TwelveDaysSong
class defined in whatever the current module is.
Ruby :: (double semi colons)
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 constant too so if you have a constant
HELLOWOLRD = 'hw'
you could call it like this ::HELLOWORLD
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