Ruby Quickies #5

Manipulating Strings

May 25, 2016 · 1 min read
it’s that simple!


x = “hello”

Can you explain the difference between:

x += “ world”


x.concat “ world”

Well, the += operator re-initializes the variable with a new value, so a += b is equivalent to a = a + b.

Therefore, while it may seem that += is mutating the value, it’s actually creating a new object and pointing the the old variable to that new object.

This is perhaps easier to understand if written as follows:

foo = “foo”
foo2 = foo
foo.concat “bar”puts foo
# => “foobar”puts foo2
# => “foobar”foo += “baz”puts foo
# => “foobarbaz”puts foo2
# => “foobar”

Examining the object_id of foo and foo2 will also demonstrate that new objects are being created.

The difference has implications in performance and also has different mutation behavior than one might expect.