0

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!

2 Answers 2

1

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"
Sign up to request clarification or add additional context in comments.

2 Comments

Thx, this works as intended and strips out all unwanted spaces!
This doesn't work if 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".
0

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.