Are strings in Ruby mutable?

SundayMonday picture SundayMonday · Dec 20, 2011 · Viewed 13.5k times · Source

Consider the following code:

$ irb
> s = "asd"
> s.object_id   # prints 2171223360
> s[0] = ?z     # s is now "zsd"
> s.object_id   # prints 2171223360 (same as before)
> s += "hello"  # s is now "zsdhello"
> s.object_id   # prints 2171224560 (now it's different)

Seems like individual characters can be changed w/o creating a new string. However appending to the string apparently creates a new string.

Are strings in Ruby mutable?

Answer

Marek Příhoda picture Marek Příhoda · Dec 20, 2011

Yes, strings in Ruby, unlike in Python, are mutable.

s += "hello" is not appending "hello" to s - an entirely new string object gets created. To append to a string 'in place', use <<, like in:

s = "hello"
s << "   world"
s # hello world