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"
?
Other objects are mutable: they have methods that change the value of the object. String is an example of an immutable type.
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 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.
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.
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>
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