What My Students Have Taught Me – Strings vs. Symbols

I had a vague idea as to the fact that symbols in Ruby take up fewer resources than strings, but I was unable to explain the how and why of it. Then after playing around with them both for a bit I discovered the following:

a = "Cheese"
=> "Cheese"
b = "Cheese"
=> "Cheese"
a.object_id
=> -608597378
b.object_id
=> -608605058
a = :Cheese
=> :Cheese
b = :Cheese
=> :Cheese
a.object_id
=> 166538
b.object_id
=> 166538

So it turns out that each symbol is one of a kind–each new variable you create with it actually points back to the first instance of it. Strings, on the other hand, create a new object every time, taking up additional space with each new variable.

Leave a Reply

You must be logged in to post a comment.