Ruby remove substring matching to any element of array
I have a string say str ="this is the string "
and i have an array of string say
array =["this is" ,"second element", "third element"]
I want to process the string such that sub string matching any of the element of array should be removed and rest of the string should be return.So i want the following output.
output: "the string "
How can i do this in ruby.
solution 1:
str = "this is the string "
array = ["this is" ,"second element", "third element"]
pattern = /\b(?:#{ Regexp.union(array).source })\b/ # => /\b(?:this\ is|second\ element|third\ element)\b/
str[pattern] # => "this is"
str.gsub(pattern, '').squeeze(' ').strip # => "the string"
solution 2:
array =["this is" ,"second element", "third element"]
str = "this is the string "
str.gsub(Regexp.union(array),'') # => " the string "