Are strings mutable in Ruby?

Aly picture Aly · Apr 16, 2011 · Viewed 24.3k times · Source

Are Strings mutable in Ruby? According to the documentation doing

str = "hello"
str = str + " world"

creates a new string object with the value "hello world" but when we do

str = "hello"
str << " world"

It does not mention that it creates a new object, so does it mutate the str object, which will now have the value "hello world"?

Answer

Dogbert picture Dogbert · Apr 16, 2011

Yes, << mutates the same object, and + creates a new one. Demonstration:

irb(main):011:0> str = "hello"
=> "hello"
irb(main):012:0> str.object_id
=> 22269036
irb(main):013:0> str << " world"
=> "hello world"
irb(main):014:0> str.object_id
=> 22269036
irb(main):015:0> str = str + " world"
=> "hello world world"
irb(main):016:0> str.object_id
=> 21462360
irb(main):017:0>