Search code examples
rubystringsymbols

What's the difference between a string and a symbol in Ruby?


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


Solution

  • The main difference is that multiple symbols representing a single value are identical 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
    

    Those are three references to the symbol :test, which are 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
    

    Those are three references to the string "test", but are 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.