Ruby Symbols
Ruby Symbols
Ruby Symbols
Symbols
Symbol is a class and the objects represent names & strings inside
the Ruby Interpreter.
If the names are simple then prefixing colon would be apt and the
literal option will be handy in case the symbols are lengthy strings.
Apart from the above there is a method “to_sym” that will convert
to symbols.
We can see the count of symbols that Ruby supports by using the
all_symbols method
Symbol.all_symbols.size # 2860
Note – The size is mentioned for the installed Ruby version 1.87.
This differs version to version
“sample_symbol”.to_sym # :sample_symbol
One can quickly raise a query why we would need Strings if they are
just representing strings! Why to use symbols?
For the benefit of all and easy/quicker understanding let’s learn this
step by step. Recollecting on Strings, Strings are nothing but
_______________________________________________________________
Page 1 of 3 Sumanth Krishna. A
Ruby Learning through Examples
collection of characters and they are mutable. That means the data
string holds subjected to change any time and interpreter can never
be aware of this change. So interpreter need to allocate memory in
case of the strings.
Let’s get into irb, and punch in the following line and repeat this 5
times
Repeating the same for 4-5 times, you should be able to notice
something like below. Note that the “object_id” reference differs
each time you punch in. This proves the point that the interpreter
needs to allocate the memory space as it does not know what data
the string is holding.
How many ever times you repeat the above, you would find that
object id is same and it’s pointing still the same space in the
memory.
_______________________________________________________________
Page 2 of 3 Sumanth Krishna. A
Ruby Learning through Examples
In Ruby on Rails, one would notice the usage of symbol more and
very effectively.
Not convinced yet! Let’s see some statistics. Copy & Paste the
below snippet as “symbol-string-benchmark.rb”
String: 13.703
Symbol: 6.813
_______________________________________________________________
Page 3 of 3 Sumanth Krishna. A