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 = "foo" # assign a variable a += "bar" # => "foobar" a << bar" # => "foobar"
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 = "bar" #assign a variable b.object_id # => 70120269506600 ObjectSpace._id2ref(70120269506600) # => "bar"
Now, let’s see what happens with the object id when you concatenate a string using the “+=” method:
a = "foo" a.object_id # => 70184094352800 b = "bar" b.object_id # => 70184090023880 a += b # => "foobar" a.object_id # => 70184082143020 a # => "foobar" ObjectSpace._id2ref(70184094352800) # => "foo"
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 = "foo" a.object_id # => 70128708494400 b = "bar" b.object_id # => 70128700542040 a << b # => "foobar" a.object_id # => 70128708494400 a # => "foobar" ObjectSpace._id2ref(70128708494400) # => "foobar"
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.