I was minding my own business and redoing my blog’s underlying engine like I tend to do every other week just because the next version will surely be more awesome than the earlier. As I was doing my rails blog app I ran into symbols.

I have used ruby for a while now and I haven’t given much thought what these funny little things called symbols are. You know the things that look like they are variables or objects but really aren’t. The ones with a colon in front of them like :post or :state_secret (and by colon I mean the two little dots not the last part of the digestive system).

Well, turns out that they are just strings. But they have magical powers. They are immutable. In some languages the concept is more apparent than in others. For instance in Objective-C where objects are immutable unless otherwise indicated.

Simply put, immutability means that the value of an object cannot be changed once initiated. You can clone or copy the object but that object does not point to the original objects location in the memory anymore, it is a brand new object.

For example we have a regular ruby string and then a ruby symbol.


Now when you print these, both of the strings would print “hello”. Ok, let’s try to change them.

puts "hello" << " world" #=> "hello world"
puts :hello << " world"  #=> undefined method `<<' for :hello:Symbol

Since :hello immutable, attempting to change the value it stores causes an error and ruby raises NoMethodError exception.

Note that we cannot change the symbols value but we can still change how the symbols value is outputted. Like in the example bellow where we change the value strings output into uppercase.

"hello".upcase #=> "HELLO"
:hello.upcase #=> "HELLO"

That’s just about all there is to it. I hope this explains what the ruby symbols are like it did to me.

Robert Sosinski wrote a nice and detailed explanation what symbols are and how they work. I suggest reading that as well. The documentation of Ruby’s symbol class is also an interesting read.