Table of Contents
A Symbol looks like a variable name but it’s prefixed with a colon(:
).
:abc
:abc.class # Symbol
:abc.object_id # 1282588 (some no)
:abc.object_id # 1282588 (same as above)
You don’t have to pre-declare a symbol and they are guaranteed to be unique.
Tip
|
Symbol is unique object and two symbols are equal if their object ids are equal. |
There’s no need to assign some kind of value to a symbol as Ruby takes care of that for you. Ruby also guarantees that no matter where it appears in your program, a particular symbol will have the same value.
Note
|
A Symbol is the most basic Ruby object you can create. It’s just a name and an internal ID. 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. |
puts "string".object_id
puts "string".object_id
puts :symbol.object_id
puts :symbol.object_id
Tip
|
If the contents (the sequence of characters) of the object are important, use a string and if the identity of the object is important, use a symbol. |
Proceed to Hash
Go back to Range
Go to Table of Content