Are strings in Ruby mutable? [duplicate]
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
Appending in Ruby String is not +=
, it is <<
So if you change +=
to <<
your question gets addressed by itself