Friday, May 2, 2008

Using Symbols

If you all are anything like me, symbols confuse the hell out of you. You may use them, but you don't really understand them. I decided to research it out a little today and see what I could figure out. It turns out that there are a lot of different viewpoints of symbols out there. Here are some articles I came across:

The first is a detailed overview of symbols, the second shows some of the way Rails uses symbols.

So, as a quick summary, here is what I know about symbols:
A symbol is used to represent strings, without the overhead of actually creating a string. They don't have the functionality that you get with a string, and the value of them can't be changed, but they are much more efficient than using a string. Here is part of the example from the Gluttonous article:

> patient1 = { "ruby" => "red" }
> patient2 = { "ruby" => "programming" }
> patient1.each_key {|key| puts key.object_id.to_s}
> patient2.each_key {|key| puts key.object_id.to_s}

The key in both hashes creates(string "ruby") has a string object created each time. So, in this example, we have 2 seperate string objects with the same name. You can achieve the same result with symbols:

> patient1 = { :ruby => "red" }
> patient2 = { :ruby => "programming" }
> patient1.each_key {|key| puts key.object_id.to_s}
> patient2.each_key {|key| puts key.object_id.to_s}

The difference here is that the same symbol is referenced in both of these. Not only is symbol a smaller object, but it gets reused.

So I am curious, what ways do you all use symbols?



Anonymous said...

My sense is that symbols are stand-in variables that reference something else. A key for a hash value. The name of a method. The symbol itself doesn't contain any useful data. It's just used as a handle on something else that's important.

Any time you need actual string data stored for some reason, never ever use a symbol. But if you just need to attach a human-readable name onto something, use a symbol.

Anonymous said...

Internally, a ruby symbol is represented by a number. Numbers can be compared much faster than strings (number comparison is a single operation, where for strings multiple characters have to be enumerated to do a comparison). Therefore, symbols are the better lookup keys for hashes, options and so on.

buy viagra online canada said...

Hi! Thanks so much for taking the time to share your post; this posting has evoked the most response.