What's the difference between a string and a symbol in Ruby and when should you use one over the other?
A symbol is something you use to represent names and strings. You would want to use a symbol when you may have need to use a string several times as this far easier and more productive.
And just found this via google, which may offer greater detail: Here you go
Symbols and strings are completely different this post has a little insight into the differences. As to when and where to use them, there is a pretty extensive post on this subject over on has many :through.
The main difference is that multiple symbols representing a single value are unique whereas this is not true with strings. For example:
irb(main):007:0> :test.object_id
=> 83618
irb(main):008:0> :test.object_id
=> 83618
irb(main):009:0> :test.object_id
=> 83618
3 references to the symbol :test, all the same object.
irb(main):010:0> "test".object_id
=> -605770378
irb(main):011:0> "test".object_id
=> -605779298
irb(main):012:0> "test".object_id
=> -605784948
3 references to the string "test", all different objects.
This means that using symbols can potentially save a good bit of memory depending on the application. It is also faster to compare symbols for equality since they are the same object, comparing identical strings is much slower since the string values need to be compared instead of just the object ids.
As far as when to use which, I usually use strings for almost everything except things like hash keys where I really want a unique identifier, not a string.
As a counterpoint, a friend of mine recently wrote a post titled "Ruby Rant" which gives another look at Ruby symbols.
An additional difference between String
and Symbol
is that a String
has a lot more methods on it for string manipulation, while a Symbol
is a relatively lean object.
Check out the documentation for the String
class and the Symbol
class.