A Symbol looks like a variable name but it's prefixed with a colon.
Examples - :action
Alternatively, you can consider the colon to mean "thing named" so :id is "the thing named id." You can also think of :id as meaning the name of the variable id, and plain id as meaning the value of the variable.
A Symbol is the most basic Ruby object you can create. It's just a name. Symbols are useful because a given symbol name refers to the same object throughout a Ruby program. Symbols are more efficient than strings. Two strings with the same contents are two different objects, but for any given name there is only one Symbol object. This can save both time and memory.
Refer the example: symbol.rb below
puts "string".object_id puts "string".object_id puts :symbol.object_id puts :symbol.object_id
The output when I ran the program
21066960 21066930 132178 132178
So if you take a look on the above, last two statements return same object as Symbol object is initialized only once. In above example :symbol is referring to same object.
So the Question is-
Therefore, when do we use a string versus a symbol?
- If the contents (the sequence of characters) of the object are important, use a string
- If the identity of the object is important, use a symbol
- The symbol object will be unique for each different name but does not refer to a particular instance of the name, for the duration of a program's execution.
We can also transform a String into a Symbol and vice-versa:
puts "string".to_sym.class # Symbol puts :symbol.to_s.class # String
- symbols can potentially save a good bit of memory depending on the application.
- It is also faster to compare symbols for equality since they are the same object, comparing identical strings is much slower since the string values need to be compared instead of just the object ids.
- Symbols are immutable: Their value remains constant.
- use Symbol when you are sure that the value will remain constant.(immutable)