Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby - can't modify frozen string (TypeError)

Tags:

ruby

Got

... '[]=': can't modify frozen string (TypeError)

when trying to modify what I thought was a copy of ARGV[0].

Same results for each of

arg = ARGV[ 0 ]
arg_cloned = ARGV[ 0 ].clone
arg_to_s = ARGV[ 0 ].to_s

arg[ 'x' ] = 'y'
arg_cloned[ 'x' ] = 'y'
arg_to_s[ 'x' ] = 'y'
like image 382
Straff Avatar asked Feb 05 '10 03:02

Straff


2 Answers

since google took too long to find the right answer ...

needed to do

arg_dup = ARGV[ 0 ].dup
like image 122
Straff Avatar answered Nov 11 '22 21:11

Straff


Since Ruby 2.3 recommended method is to use the unary plus operator, it will return a duplicated mutable string, if a string is frozen.

+arg

like image 24
DirtyF Avatar answered Nov 11 '22 19:11

DirtyF