8

What is ::?

@song ||= ::TwelveDaysSong.new
sawa
  • 165,429
  • 45
  • 277
  • 381
aarti
  • 2,815
  • 1
  • 23
  • 31
  • I knew about namespace, but I had not seen :: used without a prefix. I guess that was what confused me. I understand now that it refer's to the root level Object namespace – aarti Sep 16 '14 at 17:43

3 Answers3

11

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

shobhit1
  • 634
  • 7
  • 18
Papouche Guinslyzinho
  • 5,277
  • 14
  • 58
  • 101
3

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.

Mark Reed
  • 91,912
  • 16
  • 138
  • 175
0

Return @song

If @song is false (for instance it doesn't exist)
create a new instance of the ::TwelveDaysSong object as @song

Michael Durrant
  • 93,410
  • 97
  • 333
  • 497