Search code examples
rubystringliteralsruby-2.3

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")

Solution

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

    (+"foo").frozen? # => false
    (-"foo").frozen? # => true
    "foo".frozen? # => true