I was using gsub to replace parts of a long string from a text file, eg.
str.gsub!(/#{str1}/){"#{updates}"}
When the string became long, ruby returned an error that the string is too long. How can I solve this problem? Is there any substitute for gsub that can do the same work? As far as I know, gsub will produce a copy of the original data, which is inefficient.
If
str1is just a string rather than a regex fragment then you can do things like this:to replace the
str1part ofstrwithupdatesin place. For example:You’d have to repeat that in a loop of some sort until you got an IndexError if you wanted to replace all the
str1s instrthough.Regexes are great but your toolbox should have more than just a hammer.
BTW, if
str1is supposed to be just a string, you should be useRegexp.escapeon it before interpolating it into a regex.