Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I describe mutable strings when strings are immutable by default?

When a file has the pragma:

# frozen_string_literal: true

all strings written as literals in that file are frozen by default. When I want my strings to be immutable overall, and hence am using the pragma, but want to have a couple of mutable strings, what is the recommended way to write them?

All I can think of is:

String.new("foo")
like image 412
sawa Avatar asked Dec 13 '15 11:12

sawa


People also ask

What are mutable immutable strings?

a mutable string can be changed, and an immutable string cannot be changed. Here I want to change the value of String like this, String str="Good"; str=str+" Morning"; and other way is, StringBuffer str= new StringBuffer("Good"); str.

Is string mutable or immutable explain with example?

Other objects are mutable: they have methods that change the value of the object. String is an example of an immutable type. A String object always represents the same string. StringBuilder is an example of a mutable type.

When we say that strings are immutable What does that mean?

In Java, String objects are immutable. Immutable simply means unmodifiable or unchangeable. Once String object is created its data or state can't be changed but a new String object is created.


2 Answers

I had missed it. The recommended way is to use the +@ method string literal.

(+"foo").frozen? # => false
(-"foo").frozen? # => true
"foo".frozen? # => true
like image 71
sawa Avatar answered Oct 03 '22 06:10

sawa


You can dup the literal to make it mutable:

"foo".dup.frozen? # => false
like image 21
Vasfed Avatar answered Oct 03 '22 05:10

Vasfed