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.
ruby
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.
Best Answer
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
:my_str
will only be created once, andx
andy
point to the same area of memory. On the other hand, if you havea string containing
my_str
will be created twice, andx
andy
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).