Symbols in Ruby – Short Explanation?

When I started learning Ruby and Ruby on Rails I was introduced to the concept of symbols. You are using a lot of symbols in Rails and it feels somewhat natural after a while but when you try to explain newbies what these symbols are actually good for, it is really hard to describe. It is especially hard because you could also use strings instead. At that point you don’t actually even know the difference between a string and a symbol is or what symbols are even good for.

I just played with the interactive ruby shell => irb and found out a short way of describing what symbols are good for:


$ irb
irb(main):001:0> "foo".object_id
=> 36730
irb(main):002:0> "foo".object_id
=> 23400
irb(main):003:0> "foo".object_id
=> 10710
irb(main):004:0> :foo.object_id
=> 145858
irb(main):005:0> :foo.object_id
=> 145858
irb(main):006:0> :foo.object_id
=> 145858
irb(main):007:0>

If you would use strings to name an object in some kind of association, you would actually create new objects every time, which is quite unnecessary. Symbols are just an efficient way to point to objects or pass arguments to a method or association without creating new string objects all over the place. It is like saying »The variable or object call :foo«. Hmm got it?

I know – it is probably a no-brainer, but I had difficulties explaining it properly.

Leave a Reply

Your email address will not be published. Required fields are marked *