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!
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"
s contains two or more consecutive spaces or an element of a contains a leading or trailing space. For example, suppose s contains column headings: s = "Name Age Ht Wt" and a = [' Age', ' Wt']. Then answer_array #=> "Name Age Ht Wt".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"