Search code examples
rubystringmutable

How do I create a mutable string in Ruby?


I am using the # frozen_string_literal: true magic comment that RuboCop enforces by default, and I can't append something to a string:

string = 'hello'

string << ' world'

because it errors out with:

can't modify frozen String (RuntimeError)


Solution

  • You add a + before the string like:

    string = +'hello'
    
    string << ' world'
    
    puts(string)
    

    hello world