Pages

Thursday, August 04, 2011

ruby: strings and symbols

Symbols, is something that does not exist in perl. After reading a few good books and articles online,
I now have an understanding of symbols.

Symbols are of the Symbol class and they represent themselves just like how integers represent themselves.
For example, the number three, "3". You can't assign it anything yet you can use it.

Symbols are pretty much like a "refactored" data type of the language. Why?
Well, symbols can be used over and over again without causing memory footprints to increase.
For example, in an application that deals with address book contacts, throughtout the code, you will be declaring strings in hashes to represent "first_name", "last_name", "email" and "contact_number".

For every entry, your program has to create 5 units of memory for just the attributes.
Imagine if you had X entries. That would be 5X memory units.

In ruby, when you declare something as a symbol, it can be used over and over again.
So, in this case, you declare those attributes as symbols by sticking a colon in front of them and you have symbols.

:first_name, :last_name, :email and :contact_number. 
Besides saving space, ruby works faster with symbols as it looks them up faster. This is thanks to its symbol table which it allows the programmer to use (ie. add new symbols to). There's a speed gain there.

The following article painted a good understanding for me. I hope it helps you too.