What is ::
?
@song ||= ::TwelveDaysSong.new
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
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.
Return @song
If @song
is false (for instance it doesn't exist)
create a new instance of the ::TwelveDaysSong
object as @song