Introduction
Symbols in Ruby are a name's internal representation. The Symbol for a name is created by placing a colon(:) before the name. Regardless of how a given name is used within the program, it will always generate the same symbol by adding “:” before the name.
Symbol, it looks like a variable name, but a colon initiates it (:), as-.
:symbol :in :ruby :codingNinjas |
The symbol is the most basic Ruby object. It's nothing more than a name, and an internal ID.
Symbols are more valuable and efficient than strings because they refer to the same object throughout a Ruby program.
Two strings with the same contents are two different objects, but there is only one Symbol object for any given name. It can help you save time and remember things better.
A colon followed by a name creates a Symbol object that matches the identifier. It will make the same object for a given title or string throughout a program's execution.
Instance Method
- to_sym->sym
To_sym returns the Symbol that corresponds to an object in general. In this case, the self is returned because sym is already a symbol.
# Ruby program to illustrate the use of to_s method p :codingninjas.to_s p :"welcome to codingNinjas portal, Happy coding".to_s # .to_s, Returns the name or string corresponding to sym. |
Output:
"codingninjas" "welcome to codingNinjas portal, Happy coding" |
- intern-> sym
To_sym returns the Symbol that corresponds to an object in general. In this case, because sym is already a symbol, self is born.
We can use Symbols objects to represent methods, variables, and other identifiers. Some methods require a symbol, such as defining a method, method missing, and trace var. A string can also be passed to other methods, such as attr accessor, send, or autoloaded.
Symbols are frequently used as hash keys because they are only created once. A new object is created every time a string hash key is used, resulting in some memory overhead. For symbol hash keys, there is even a special Syntax:
name_1 = { :name => "rohit", :age => 32 } name_2 = { name: "mohit", age: 12 } |
Output:
{"name"=>"mohit", "age"=>12} |
"Use a String if the object's textual content is important. Use a Symbol if the object's identity is essential."