75

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'
1
  • ARGV comes with strings in a frozen state ARGV.map(&:dup) will return an array with the same non-frozen strings.
    – ribamar
    Jan 24, 2019 at 17:59

3 Answers 3

133

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

needed to do

arg_dup = ARGV[ 0 ].dup
6
  • 14
    Right. Clone copies the object's entire state, including frozen status. Dup copies the meat of the object without those other flags.
    – Eli
    Feb 5, 2010 at 4:04
  • 1
    quite surprised that .to_s does the same (including frozen)!?
    – Straff
    Feb 5, 2010 at 10:08
  • 3
    64 seconds from the posting of your question, to searching Google and getting irritated to posting your answer was too long? :)
    – vgoff
    Oct 3, 2013 at 21:54
  • 18
    much more than that ... did lots of google searching which took ages to find right result. Then I posted this question and the answer so "stack" has it and it's easily findable now (for when I forget). Number 1 hit in google now!
    – Straff
    Oct 5, 2013 at 9:44
  • In 2.1.0, Object#dup does not copy frozen state.
    – Nate Symer
    Jun 4, 2014 at 0:34
25

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

0

if you want to concat so just needed to do use in this way

'+'.dup.concat('123456789') # +123456789

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.