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")
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.
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.
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.
I had missed it. The recommended way is to use the +@
method string literal.
(+"foo").frozen? # => false
(-"foo").frozen? # => true
"foo".frozen? # => true
You can dup
the literal to make it mutable:
"foo".dup.frozen? # => false
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