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

2

8

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")
Factional answered 13/12, 2015 at 11:14 Comment(3)
Was just going to say dup too. It's just that this is the cool new stuff and the community doesn't have a convention on it yet.Muskmelon
@ndn I don't care about convention. What matter is conciseness, readability, performance, etc.Factional
there is no new syntax like "foo"u if that is what you are asking. You can't get more concise than Object#dup. As for performance, I would be surprised if String.new is significantly better.Muskmelon
F
8

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

(+"foo").frozen? # => false
(-"foo").frozen? # => true
"foo".frozen? # => true
Factional answered 15/12, 2015 at 3:34 Comment(0)
S
4

You can dup the literal to make it mutable:

"foo".dup.frozen? # => false
Strake answered 13/12, 2015 at 11:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.