Ruby match first occurrence of string for a gsub replacement

14,839

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

Share:
14,839
ar3
Author by

ar3

Who-I-Am:Father.Husband.Son.Brother.Friend.ProudMentor.CuriousMentee Makes-Me-Tick:Software Architect by training...Inventor by spirit

Updated on June 28, 2022

Comments

  • ar3
    ar3 almost 2 years

    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:")
    
  • ar3
    ar3 almost 13 years
    Thank you! I'm...just getting started with RoR, and the language/framework is still a little uncomfortable...I'm a C#/JS guy.
  • HRÓÐÓLFR
    HRÓÐÓLFR almost 13 years
    At least you've seen the light :D