user2128702
user2128702

Reputation: 2121

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.

Upvotes: 12

Views: 14482

Answers (3)

builder-7000
builder-7000

Reputation: 7627

Use the String#[] method:

phrase["foo"] = ""

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

Upvotes: 1

ctide
ctide

Reputation: 5257

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

Upvotes: 2

JaTo
JaTo

Reputation: 2832

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.

Upvotes: 21

Related Questions