2

I am a beginner in Ruby and I am trying to wrap my head around symbols. Would you say that my current understanding, summarized in the following (oversimplified) definition, is true for most purposes?

"A symbol is a string constant with its name also being its content."

And if this is true, why don't we just use string constants in its place?

(What is a symbol in Ruby? is a duplicate, but the answers were not 100% clear for me and I cannot comment there due to low reputation)

3

My sense is you have to consider how the underlying Symbol is created, represented and referenced in comparison to a String. Why?

Well, both Symbols and Strings appear similar in description, yet the application and the computers internal representation of them is uniquely different.

  • A string is used to store a string value, the value can be changed after creation.

  • A symbol is used to store a string value, the value cannot be changed after creation. All references to the Symbol point to the same location in memory.

If you copy a symbol you have two names but one memory location, if you copy a String the assignment operation creates a new memory object and copies the content of the string object into the storage of the second memory object. Thus, you have two names and two memory locations.

irb(main):002:0> symbol = :symbol
=> :symbol
irb(main):003:0> symbol.object_id
=> 824028
irb(main):004:0> symbol2 = symbol
=> :symbol
irb(main):005:0> symbol2.object_id
=> 824028

A symbol only has one memory instance to point too. Now lets consider a string:

irb(main):006:0> stringName = "Fred"
=> "Fred"
irb(main):007:0> stringName.object_id
=> 70308031841340
irb(main):008:0> stringName2 = stringName
=> "Fred"
irb(main):009:0> stringName2.object_id
=> 70308031841340
irb(main):010:0> stringName2 = "Frederick"
=> "Frederick"
irb(main):011:0> stringName.object_id
=> 70308031841340
irb(main):012:0> stringName2.object_id
=> 70308032061840
irb(main):013:0> stringName2 = "Fred"
=> "Fred"
irb(main):014:0> stringName.object_id
=> 70308031841340
irb(main):015:0> stringName2.object_id
=> 70308032090380
irb(main):016:0> stringName
=> "Fred"
irb(main):017:0> stringName2
=> "Fred"

as you can see the String upon copy creates a new object in memory that is a copy of the first. As soon as you change its content it creates a new object in memory to store the unique string from the first instance even if the string is the same. (i.e. "Fred")

Why use symbols?

Symbols are far more efficient in the use of memory than strings. Further, they are uniquely applicable to reference items you wish to refer to in your code. Once created they are guaranteed to stay the same.

I hope the above points you in the right direction.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.