What My Students Have Taught Me – String Concatenation

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.

When working on some exercises one of my students asked me the difference between the blocks of code below.

Block 1

a = "Poo"
=> "Poo"
b = "del"
=> "del"
a += b
=> "Poodel"

Block 2

a = "Poo"
=> "Poo"
b = "del"
=> "del"
a << b
=> "Poodel"

My first instinct was that they were essentially the same, but then my student pointed out to me the following example:

Example 1

a = "Poo"
=> "Poo"
b = a
=> "Poo"
b += "del"
=> "Poodel"
a
=> "Poo"

Example 2

a = "Poo"
=> "Poo"
b = a
=> "Poo"
b << "del"
=> "Poodel"
a
=> "Poodel"

So it turns out the operators are different. In both cases, both a and b start out pointing at the same object. In the case of the shovel operator (<<) the object itself is changed. In the case of += it helps to be aware that this actually expands to b = b + "del", or rather, b = "Poo" + "del", which creates an entirely new string instance, pointing b at it and leaving a and its "Poo" alone.

This situation bears the question which operator is better to use. It depends on the situation, of course, but chances are, unless you can think of a good reason not to, you'll be better off using <<, as it leaves you with one object instead of two. If you don't need to reuse the original object it makes no sense to keep it lying around. It may seem like a small price to store an extra string, but it can quickly become a space hog if you're looping over thousands of strings patching them together.

Leave a Reply

You must be logged in to post a comment.