Skip to content

Latest commit

 

History

History
55 lines (38 loc) · 1.58 KB

symbol.adoc

File metadata and controls

55 lines (38 loc) · 1.58 KB

Symbol

Overview

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.

Try yourself

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.

Next Topic

Proceed to Hash

Previous Topic

Go back to Range

Table of Content