After reading Kevin Clark's recent post on Ruby symbols made me want to learn more about this mysterious part of the Ruby language. After writing some unit tests to ensure that a symbol really is the same object as any other with the same name, I have come to the following conclusion: symbols are immutable string objects, same named symbols share the same object and therefore the same
Kevin's example points out that they make great keys for hashs, and other indicators of what action to take (
Coming from a Java background, symbols have made me hit my head a number of times, this rather helpful post from Rob Sanheim helped clear things up a lot for me.
Why the lucky stiff also has a good explaination, he suggests:
Symbols are words that look just like variables. Again, they may contain letters, digits, or underscores. But they start with a colon.
:a, :b, or :ponce_de_leon are examples.
Symbols are lightweight strings. Usually, symbols are used in situations where you need a string but you won’t be printing it to the screen.
You could say a symbol is a bit easier on the computer. It’s like an antacid. The colon indicates the bubbles trickling up from your computer’s stomach as it digests the symbol. Ah. Sweet, sweet relief.
So I've got a number of different explainations of symbols, I've written 5 unit tests about them, but I'm still not 100% sure of all their uses. I suppost I just need to get Rails installed and start playing with that to really see how symbols should be used...
Technorati Tags: Ruby, Kevin Clark, Rob Sanheim, Why The Lucky Stiff, Ruby on Rails, Andrew Beacock