Explain the difference between

Technology CommunityCategory: RubyExplain the difference between
VietMX Staff asked 2 years ago


x = "hello"

Explain the difference between:

x += " world"


x.concat " world"

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 for performance and also has different mutation behavior than one might expect.