tags:

views:

711

answers:

6

What's the difference between a string and a symbol in Ruby and when should you use one over the other?

+4  A: 

The first thing to pop up in Google might be useful to you:

13 Ways of Looking at a Ruby Symbol

Thomas
+1  A: 

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

websch01ar
A: 

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.

Mr. Matt
+10  A: 

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.

Robert Gamble
Although symbols are not cleaned up by the garbage collector and stick around until the end of the runtime instance. So if you declare a lot of symbols you might be wasting a lot of memory.
Daemin
@Daemin: This is generally a non-issue unless you are dynamically creating symbols en-masse. This is the cause of memory ballooning in some apps. If you use hard-coded symbols in your code, you are relatively safe.
Pistos
A: 

As a counterpoint, a friend of mine recently wrote a post titled "Ruby Rant" which gives another look at Ruby symbols.

Greg Hewgill
Symbols can be very useful and provide better performance than options that other languages offer but, like almost anything else, can also be abused. Point 4a re:APIs can be a big PITA but this is largely addressed in Ruby 1.9 where Symbols can be compared with strings directly, among other things.
Robert Gamble
A: 

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.

nertzy