Archive for December, 2010

What My Students Have Taught Me – Strings vs. Symbols

Tuesday, December 7th, 2010

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.

What My Students Have Taught Me – String Concatenation

Sunday, December 5th, 2010

I’ve been teaching a beginners’ Ruby programming class for a couple of months now, and one of the benefits of teaching is that students are full of tough questions that push me to step my game up. Sometimes I know the answer, others I’m not sure, but I have a pretty solid guess–and once in a while a student says, “But that doesn’t make sense” and proves me wrong. Here’s an item from the latter category.
(more…)