I have this code:
settings[:base_name].gsub! /[\x00\/\\:\*\?\"<>\|]/, ''
When I run the script it throws an error:
gsub!': can't modify frozen String (RuntimeError)
I have changed the code to this:
settings[:base_name] = settings[:base_name].gsub /[\x00\/\\:\*\?\"<>\|]/, ''
The code above works, but I don’t like at all, is there a way to properly use gsub! in this case?
No. Apparently, the API providing the string has frozen it, which means any method that modifies it will fail. Because
gsub!modifies the string it is called on, a frozen object can not usegsub!. However, the variable that contains a frozen object can still be set to a non-frozen object, which is why your second code snippet works.The API probably froze the object because it is a constant string that all of the instances share, and so one instance shouldn’t be able to ruin the string. But they do define a setter method, so you can set the value.