Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are strings mutable in Ruby?

Are Strings mutable in Ruby? According to the documentation doing

str = "hello" str = str + " world" 

creates a new string object with the value "hello world" but when we do

str = "hello" str << " world" 

It does not mention that it creates a new object, so does it mutate the str object, which will now have the value "hello world"?

like image 958
Aly Avatar asked Apr 16 '11 12:04

Aly


People also ask

Are strings are mutable?

Other objects are mutable: they have methods that change the value of the object. String is an example of an immutable type.

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.

Are strings really immutable?

String is immutable ( once created can not be changed ) object . The object created as a String is stored in the Constant String Pool. Every immutable object in Java is thread safe ,that implies String is also thread safe . String can not be used by two threads simultaneously.

Are symbols immutable in Ruby?

Because symbols are immutable, Ruby doesn't have to allocate more memory for the same symbol. That is because it knows that once it put the value in memory, it will never be changed, so it can reuse it. You can easily see this by looking at their object IDs.


1 Answers

Yes, << mutates the same object, and + creates a new one. Demonstration:

irb(main):011:0> str = "hello" => "hello" irb(main):012:0> str.object_id => 22269036 irb(main):013:0> str << " world" => "hello world" irb(main):014:0> str.object_id => 22269036 irb(main):015:0> str = str + " world" => "hello world world" irb(main):016:0> str.object_id => 21462360 irb(main):017:0> 
like image 103
Dogbert Avatar answered Oct 02 '22 09:10

Dogbert