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")
sawa
  • 165,429
  • 45
  • 277
  • 381
  • 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. – ndnenkov Dec 13 '15 at 11:25
  • @ndn I don't care about convention. What matter is conciseness, readability, performance, etc. – sawa Dec 13 '15 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. – ndnenkov Dec 13 '15 at 12:12

2 Answers2

8

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

(+"foo").frozen? # => false
(-"foo").frozen? # => true
"foo".frozen? # => true
sawa
  • 165,429
  • 45
  • 277
  • 381
4

You can dup the literal to make it mutable:

"foo".dup.frozen? # => false
Vasfed
  • 18,013
  • 10
  • 47
  • 53