Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 965
Iulian Onofrei Avatar asked Aug 25 '26 00:08

Iulian Onofrei


2 Answers

You add a + before the string like:

string = +'hello'

string << ' world'

puts(string)

hello world

like image 117
Iulian Onofrei Avatar answered Aug 26 '26 22:08

Iulian Onofrei


You can also use +=:

s = 'H'
s += 'ello

=> "Hello"

like image 22
jamesc Avatar answered Aug 26 '26 20:08

jamesc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!