What's the difference between a string and a symbol in Ruby and when should I use one over the other?
While symbols and strings give you the same results when used as keys in hashes, they are not the same thing. A symbol is immutable while a string is mutable. You can't change a symbol once it's created. :locked on different lines in your code is the same object.
What's a Symbol in Ruby? A symbol is a unique instance of the Symbol class which is generally used for identifying a specific resource.
A string is a sequence of one or more characters that may consist of letters, numbers, or symbols. Strings in Ruby are objects, and unlike other languages, strings are mutable, which means they can be changed in place instead of creating new strings. You'll use strings in almost every program you write.
Symbol is the most basic Ruby object we can create. It's just a name and an internal ID. Since a given symbol name refers to the same object throughout a Ruby program, Symbols are useful and more efficient than strings.
What are the differences between Symbols and Strings?
split
on Symbols.From Understanding Differences Between Symbols & Strings in Ruby
If you know Chinese, you can also read 理解 Ruby Symbol.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With