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")
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. Commented Dec 13, 2015 at 11:25
  • @ndn I don't care about convention. What matter is conciseness, readability, performance, etc. Commented Dec 13, 2015 at 11:40
  • 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. Commented Dec 13, 2015 at 12:12

2 Answers 2

8

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

(+"foo").frozen? # => false
(-"foo").frozen? # => true
"foo".frozen? # => true
Sign up to request clarification or add additional context in comments.

Comments

4

You can dup the literal to make it mutable:

"foo".dup.frozen? # => false

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.