Colons in :ruby
Learning small things every day
Being curious when learning a new programming language could lead to discover new things that could potentially help you understand the language a bit better.
I am currently creating a game in Ruby and in my code I have been using colons multiple times but I didn’t no why until today.
I was curious about what a colon meant in Ruby.
When I first started learning Ruby, I assumed that the colon before a name was a variable. And I used it in my code as a variable and it seemed to work, so I never actually googled why I was using the colon.
But today, out of curiosity, I have discovered that it isn’t a variable, it’s a symbol instead.
A symbol might be a bit confusing to understand at the beginning, so I will try to explain what it is in this post to help you get out that of the way.
Symbols are a way to represent strings and names in ruby.
The main difference between symbols and strings is that symbols of the same name are initialised and exist in memory only once.
And I was totally wrong. Symbols are not variables. A variable in Ruby is a handle to an object of some sort, and that object may be a symbol.
If you are wondering why do we use symbols in Ruby instead of strings, I will point out an example of when and why using symbols is more effective than using strings:
Symbols are commonly used when using strings would result in a lot of repetition.
For instance, we have two hash that each stores a string a value:
hash1 = { "string" => "value"}
hash2 = { "string" => "value"}
This creates six objects in memory (four string objects and two hash object).
If we consider using a symbol instead, we will have:
hash1 = { :symbol => "value"}
hash2 = { :symbol => "value"}
This only creates five objects in memory (one symbol, two strings and two hash objects).
Since :symbol always resolves back to the same location in memory it can be reused across multiple hash instances with almost no increase in memory.
Just to clarify, in both cases, the value is not being stored in a symbol or a string, it is being stored in a hash.
It might be difficult to understand as symbols are super simple.