What’s << Got To Do With It

Strings and Shovels! Strings and Shovels!

Now, back to being serious 🙂 If you’d like to concatenate a string in Ruby, there are a few ways of doing that, mainly:


a = &quot;foo&quot; # assign a variable

a += &quot;bar&quot; # =&gt; &quot;foobar&quot;

a &lt;&lt; bar&quot; # =&gt; &quot;foobar&quot;

While both the “+=” and the “<<” (shovel) methods return the same results, there is actually a pretty important difference between them.


When you assign a variable in Ruby and other object-oriented programming languages, that object gets an object id, which is the location of that object in memory:

b = &quot;bar&quot; #assign a variable

b.object_id # =&gt; 70120269506600
ObjectSpace._id2ref(70120269506600) # =&gt; &quot;bar&quot;

Now, let’s see what happens with the object id when you concatenate a string using the “+=” method:

a = &quot;foo&quot;
a.object_id # =&gt; 70184094352800

b = &quot;bar&quot;
b.object_id # =&gt; 70184090023880

a += b # =&gt; &quot;foobar&quot;

a.object_id # =&gt; 70184082143020
a # =&gt; &quot;foobar&quot;
ObjectSpace._id2ref(70184094352800) # =&gt; &quot;foo&quot;

As you can see, when you use the “+=” method, the new value “foobar” creates a new object in memory. The original value “foo” is still stored in memory as well, but is no longer assigned to the variable “a”.

Now, the shovel method:

a = &quot;foo&quot;
a.object_id # =&gt; 70128708494400

b = &quot;bar&quot;
b.object_id # =&gt; 70128700542040

a &lt;&lt; b # =&gt; &quot;foobar&quot;

a.object_id # =&gt; 70128708494400
a # =&gt; &quot;foobar&quot;
ObjectSpace._id2ref(70128708494400) # =&gt; &quot;foobar&quot;

As you see, with the shovel (<<) method, the original object “foo” is modified to “foobar” and no new object is created.

So why is this important?

When you are running a program with millions of users, the creation of new objects in memory using the “+=” method will significantly slow down your program.

Enjoy the article? Join over 17,500+ Swift developers and enthusiasts who get my weekly updates.