Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are strings in Ruby mutable? [duplicate]

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?

like image 964
SundayMonday Avatar asked Dec 20 '11 18:12

SundayMonday


People also ask

Are strings mutable Ruby?

In most languages, string literals are also immutable, just like numbers and symbols. In Ruby, however, all strings are mutable by default.

What does it mean that strings are immutable in Ruby?

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.

Is strings are mutable or immutable?

String is an example of an immutable type. A String object always represents the same string. StringBuilder is an example of a mutable type.

Are Ruby variables mutable?

In Ruby, numbers and boolean values are immutable. Once we create an immutable object, we cannot change it.


2 Answers

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 
like image 177
Marek Příhoda Avatar answered Sep 19 '22 09:09

Marek Příhoda


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

like image 20
zed_0xff Avatar answered Sep 20 '22 09:09

zed_0xff