Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove the first occurence of a substring in string?

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.

like image 786
user2128702 Avatar asked Nov 29 '13 02:11

user2128702


3 Answers

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.

like image 80
JaTo Avatar answered Oct 07 '22 02:10

JaTo


Use the String#[] method:

phrase["foo"] = ""

For comparison, in my system this solution is 17% faster than String#sub!

like image 37
builder-7000 Avatar answered Oct 07 '22 02:10

builder-7000


sub will do what you want. gsub is the global version that you're probably already familiar with.

like image 35
ctide Avatar answered Oct 07 '22 02:10

ctide