Ruby - Module Symbols


Symbols are abstract references.

It is represented by a string prefixed with a colon.

For example, :blue, :good, and :name.

Here is an example.


current_situation = :good 
puts "Everything is fine" if current_situation == :good 
puts "PANIC!" if current_situation == :bad


Here, :good and :bad are symbols.

Symbols don't contain values or objects.

They're used as a consistent name within code.

Symbols is like literal constants with no value.

Symbols are useful when creating hashes:

s = { :key => 'value' } 

This is useful when there's a specification or consistency in which key names to use:

person1 = { :name => "Json", :age => 20, :gender => :male } 
person2 = { :name => "XML", :age => 23, :gender => :female }  

Related Topic