This question already has an answer here:
- Are strings mutable in Ruby? 2 answers
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?
Appending in Ruby String is not
+=
, it is<<
So if you change
+=
to<<
your question gets addressed by itselfRuby Strings are mutable. But you need to use << for concatenation rather than +.
In fact concatenating string with
+ operator(immutable) because it creates new string object.
<< operator(mutable) because it changes in the same object.
From what I can make of this pull request, it will become possible in Ruby 3.0 to add a "magic comment" that will make all string immutable, rather than mutable.
Because it seems you have to explicitly add this comment, it seems like the answer to "are string mutable by default?" will still be yes, but a sort of conditional yes - depends on whether you wrote the magic comment into your script or not.
EDIT
I was pointed to this bug/issue on Ruby-Lang.org that definitively states that some type of strings in Ruby 3.0 will in fact be immutable by default.
Yes, strings in Ruby, unlike in Python, are mutable.
s += "hello"
is not appending"hello"
tos
- an entirely new string object gets created. To append to a string 'in place', use<<
, like in:Strings in Ruby are mutable, but you can change it with freezing.
so, Strings are mutable, but
+=
operator creates a new String.<<
keeps old