Ruby - can't modify frozen string (TypeError)

Ruby

Ruby Problem Overview


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'

Ruby Solutions


Solution 1 - Ruby

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

needed to do

arg_dup = ARGV[ 0 ].dup

Solution 2 - Ruby

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionStraffView Question on Stackoverflow
Solution 1 - RubyStraffView Answer on Stackoverflow
Solution 2 - RubyDirtyFView Answer on Stackoverflow