Ruby String#sub! and String#gsub!

(Everyday Code – instead of keeping our knowledge in a let’s share it with the internet)

In Ruby String#sub! is different from String#gsub!. That much we know. But I am so used to .gsub that could not even see that the code in question uses .sub

This one got me today. In the code we had

self.text_content.sub!(/\( %7B%7B(%20)*/, "( {{ ")

I went over to change the regex because of a new requirement and I deployed and published on production.

But String#sub! replaces only the first occurrence of the regex, not all the occurrences. I could not event see that it was #sub! used and not #gsub!. Why would somebody one to replace only the first occurrence for this case – I don’t know.