I'm totally new to the Ruby world, and I'm a bit confused with the concept of Symbols. What's the difference between Symbols and Variables? Why not just using variables?
Thanks.
Software Engineering Stack Exchange is a question and answer site for professionals, academics, and students working within the systems development life cycle. It only takes a minute to sign up.
Sign up to join this communityI'm totally new to the Ruby world, and I'm a bit confused with the concept of Symbols. What's the difference between Symbols and Variables? Why not just using variables?
Thanks.
Variables and symbols are different things. A variable points to different kinds of data. In Ruby, a symbol is more like a string than a variable.
In Ruby, a string is mutable, whereas a symbol is immutable. That means that only one copy of a symbol needs to be created. Thus, if you have
x = :my_str
y = :my_str
:my_str
will only be created once, and x
and y
point to the same area of memory. On the other hand, if you have
x = "my_str"
y = "my_str"
a string containing my_str
will be created twice, and x
and y
will point to different instances.
As a result, symbols are often used as the equivalent to enums in Ruby, as well as keys to a dictionary (hash).
#mySymbol
.
Dec 8, 2010 at 15:33
Symbol in Ruby is basically the same thing as symbol in real world. It is used to represent or name something.
Symbols are very commonly used to represent some kind of state, for example
order.status = :canceled
order.status = :confirmed
You can also look at symbol as instant enum. You don't need to define a symbol, you just use it. This article explains it in great detail.
Usually, variables tend to be confused with strings, but I can understand you thinking it like a variable. It's understandable. Think of it this way:
The status of a player in a game is represented by a number. 1 means alive, 2 means unsure, 3 means dead. This can easily be replaced by symbols. The symbols could be :alive
:unsure
and :dead
. To check if a player is alive, instead of doing this:
if player_status == 1
You could do this:
if player_status == :alive