Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby match first occurrence of string for a gsub replacement

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:") 
like image 555
ar3 Avatar asked Jul 21 '11 20:07

ar3


People also ask

How do you replace a string in Ruby?

To replace a word in string, you do: sentence. gsub(/match/, "replacement") .

What does .gsub mean in Ruby?

gsub! is a String class method in Ruby which is used to return a copy of the given string with all occurrences of pattern substituted for the second argument. If no substitutions were performed, then it will return nil. If no block and no replacement is given, an enumerator is returned instead.

What is the difference between gsub () and sub ()?

The sub() and gsub() function in R is used for substitution as well as replacement operations. The sub() function will replace the first occurrence leaving the other as it is. On the other hand, the gsub() function will replace all the strings or values with the input strings.

What is GSUB in regex?

The “sub” in “gsub” stands for “substitute”, and the “g” stands for “global”. Here is an example string: str = "white chocolate" Let's say that we want to replace the word “white” with the word “dark”. Here's how: str.gsub("white", "dark")


1 Answers

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

like image 106
HRÓÐÓLFR Avatar answered Oct 08 '22 02:10

HRÓÐÓLFR