Jan Hofmann
Jan Hofmann

Reputation: 77

How to remove array items from string?

I have this string: This is my example #foo and #bar

And this array: ['#foo','#bar']

And this is the string I would like to have: This is my example and

Thx!

Upvotes: 0

Views: 112

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110665

The following preserves whitespace:

str = 'This    is my example   #foo and #bar'
arr = ['#foo','#bar']

r = Regexp.new arr.each_with_object('') { |s,str| str << s << '|' }[0..-2]
  #=> /#foo|#bar/
str.gsub(r,'')
  #=> "This    is my example and "

Another example (column labels):

str = "    Name        Age        Ht        Wt"
arr = ['        Age', '        Wt']

r = Regexp.new arr.each_with_object('') { |s,str| str << s << '|' }[0..-2]
  #=> /        Age|        Wt/
str.gsub(r,'')
  #=> "    Name        Ht"

Upvotes: 0

Sagar Pandya
Sagar Pandya

Reputation: 9497

Define your string and array:

s = "This is my example #foo and #bar"
a = ['#foo', '#bar']

Then:

answer_array = (s.split(" ") - a).join(" ")

Gives the answer:

=> "This is my example and"

Upvotes: 1

Related Questions