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}
211006
> patient2.each_key {|key| puts key.object_id.to_s}
203536
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}
3918094
> patient2.each_key {|key| puts key.object_id.to_s}
3918094
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?
-Ralph