How can I remove the first occurence of a given substring?
I have:
phrase = "foobarfoo"
and, when I call:
phrase.some_method_i_dont_know_yet ("foo")
I want the phrase to look like barfoo
.
I tried with delete
and slice
but the first removes all the occurrences but the second just returns the slice.
Use sub!
to substitute what you are trying to find with ""(nothing), thereby deleting it:
phrase.sub!("foo", "")
The !(bang) at the end makes it permanent. sub
is different then gsub
in that sub
just substitutes the first instance of the string that you are trying to find whereas gsub
finds all instances.
Use the String#[]
method:
phrase["foo"] = ""
For comparison, in my system this solution is 17% faster than String#sub!
sub
will do what you want. gsub
is the global version that you're probably already familiar with.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With