Ruby match first occurrence of string for a gsub replacement

ar3 picture ar3 · Jul 21, 2011 · Viewed 14.1k times · Source

I have a string let's say http://someUrul.com/someController/SOmeAction?SomeQS=http://someOtherUrl

and I want to replace the first http with https, but not the second, so I end up with https://someUrul.com/someController/SOmeAction?SomeQS=http://someOtherUrl

How can I accomplish this with a simple gsub? The following replaces both.

request.url.gsub(/http:/, "https:")

Answer

HRÓÐÓLFR picture HRÓÐÓLFR · Jul 21, 2011

Use sub, not gsub. gsub is global, sub isn't.