Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does :: mean in Ruby syntax? [duplicate]

Tags:

ruby

What is ::?

@song ||= ::TwelveDaysSong.new
like image 682
aarti Avatar asked Sep 14 '14 01:09

aarti


People also ask

What does :: mean in Ruby documentation?

Use :: for describing class methods, # for describing instance methods, and use . for example code.

What does :: mean in rails?

:: Lets you access a constant, module, or class defined inside another class or module.

What does two colons mean in Ruby?

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 do colons mean in Ruby?

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.


2 Answers

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.

like image 32
Mark Reed Avatar answered Sep 30 '22 18:09

Mark Reed


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

like image 183
Papouche Guinslyzinho Avatar answered Sep 30 '22 16:09

Papouche Guinslyzinho