Yet Another Blog about Ruby Symbols

by Caleb Tennis

I really like Austin's earlier blog about Symbols and how they are just names.

I think the real confusion around symbols is three fold:

  1. The colon in the name

  2. The name Symbol

  3. How they relate to Strings


2005-12-30 17:47:34
Thanks for that excellent explanation. I have one problem with symbols which is keeping me from using them consistently.

It seems symbols are often used in hashes like this: { :name => 'John Smith', :age => 54 }

When using symbols for keys, you need to use a symbol when retrieving the value as well. For example, hash['first_name'] would return nil in the last example because the key is actually a symbol (not a string). But, some APIs return hashes with string keys (such as the MySQL's fetch_hash method). This forces me to keep track of which hashes have string keys and which have symbol keys.

Because of this I decided to always use strings for hash keys. The only downside I can think of to using strings is the performance hit, but I can't think of any other alternative which will not cause a performance hit.

2005-12-31 13:32:52
I think all this talk about symbols is cool. I feel like we're getting somewhere, and once the sufficent babble has been disseminated future googlers will have a treasure trove of info.


2006-01-01 14:04:22
I think one of the main advantages of Symbols in Ruby is purely aesthetic - they make library and framework APIs in Ruby 'look' a lot more like little domain specific langauges than in other languages.
2006-01-02 15:00:45
Sorry, I should have said hash['name'] instead of hash['first_name'] in my last comment.
2006-03-27 22:59:53
Of course, you could use:


but your point is correct: Symbol(s) and String(s) cannot be used interchangably as keys to a hash.