Ruby - What are Symbols? When and How Do I Use Them

September 23, 2014

Ruby has a built-in class called Symbol, Symbols are very interesting in that I have not seen anything similar in C#, Java or JavaScript. I think of Symbols being similar to Enums and somewhat string-ish. Symbols are immutable meaning their value can not be changed once set.

Running any of this code will result in a NoMethodError:

:abc + :a
:abc + a
:abc + 'a'
:abc << :a

So as you can see there is no appending or adding of any strings or Symbols to another Symbol. This immutability is great as it gives us a great why to represent something that is unique. Symbols can’t change thus they are unique. The Symbol ‘:abcd’ no matter where it is called in you code is the same ‘:abcd’ object. You can test this out in IRB, first let’s look how two strings with the same value have different ‘object_ids’:

 => 70277954526800
 => 70277954509020

Now compare that with two Symbols that have the same value:

 => 541448
 => 541448

Le bam! Same Symbol same ‘object_id’. This makes Symbols perfect to use as keys in a Hash / Dictionary. Symbols are very unknown coming from the .NET world but are pretty straight-forward and are an excellent tool in the belt.

Discussion, links, and tweets

My name is Deon Heyns and I am a developer learning things and documenting them in realtime. Python, Ruby, Scala, .NET, and Groovy are all languages I have written code in. I appeared in the New York Post once. I host my code up at GitHub and Bitbucket so have a look at my code, fork it and send those pull requests.

comments powered by Disqus