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?
In most languages, string literals are also immutable, just like numbers and symbols. In Ruby, however, all strings are mutable by default.
An immutable object is an object whose state cannot be modified after it is created. As immutable objects state cannot be changed it doesn't make sense to copy the same object over and over. In fact, Ruby 2.3 (with frozen strings enabled) will hold a unique instance for each string literal value used in the program.
String is an example of an immutable type. A String object always represents the same string. StringBuilder is an example of a mutable type.
In Ruby, numbers and boolean values are immutable. Once we create an immutable object, we cannot change it.
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
ruby-1.9.3-p0 :026 > s="foo" => "foo" ruby-1.9.3-p0 :027 > s.object_id => 70120944881780 ruby-1.9.3-p0 :028 > s<<"bar" => "foobar" ruby-1.9.3-p0 :029 > s.object_id => 70120944881780 ruby-1.9.3-p0 :031 > s+="xxx" => "foobarxxx" ruby-1.9.3-p0 :032 > s.object_id => 70120961479860
so, Strings are mutable, but +=
operator creates a new String. <<
keeps old
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With