Ruby - What are Symbols? When and How Do I Use Them
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’:
'abcd'.object_id => 70277954526800 'abcd'.object_id => 70277954509020
Now compare that with two Symbols that have the same value:
:abcd.object_id => 541448 :abcd.object_id => 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.