Linus
Linus

Reputation: 2819

Remove phrases in Array from string

I need to remove some phrases from a string in Ruby. The phrases are defined inside an array. It could look like this:

remove = ["Test", "Another One", "Something Else"]

Then I want to check and remove these from a given string.

"This is a Test" => "This is a " "This is Another One" => "This is " "This is Another Two" => "This is Another Two"

Using Ruby 1.9.3 and Rail 3.2.6.

Upvotes: 2

Views: 572

Answers (2)

Phrogz
Phrogz

Reputation: 303559

Simplest (but not most efficient):

# Non-mutating
cleaned = str
remove.each{ |s| cleaned = cleaned.gsub(s,'') }

# Mutating
remove.each{ |s| str.gsub!(s,'') }

More efficient (but less clear):

# Non-mutating
cleaned = str.gsub(Regexp.union(remove), '')

# Mutating
str.gsub!(Regexp.union(remove), '')

Upvotes: 1

mogelbrod
mogelbrod

Reputation: 2315

ary = ["Test", "Another One", "Something Else", "(RegExp i\s escaped)"]
string.gsub(Regexp.union(ary), '')

Regexp.union can be used to compile an array of strings (or regexpes) into a single regexp which therefore only requires a single search & replace.

Regexp.union ['string', /regexp?/i] #=> /string|(?i-mx:regexp?)/

Upvotes: 5

Related Questions