1

I want check a long string against array of words and select the matching words. The words could be multi-words such as or This is or more. This is what I have so far.

str = "This is a demo text for demo..."
w = ["This is", "to", "is", "for demo"]     
w.select{ |w| str.include?w } #=>["This is", "is", "for demo"] 

but in this I don't want my result to have "in", "get" etc

str = "This is a demo text for demo together within..."
w = ["This is", "to", "is", "for demo", "in", "get"]    
w.select{ |w| str.include?w } #=> ["This is", "to", "is", "for demo", "in", "get"]

str.include?w is doing what it is supposed to do. Are there any alternatives?

2
  • try w.select{ |w1| str.include?(w1 + " ") } Commented Mar 3, 2014 at 16:43
  • That's not enough, Alok. SO wants 'in' excluded when str = '...within the...' and included when str = '...jumped in'. Commented Mar 3, 2014 at 22:16

1 Answer 1

5
str = "This is a demo text for demo..."
w = ["This is", "to", "is", "for demo"]     
p w.select{|w|str =~ /\b#{w}\b/ }

The \b in the regexp is a word boundary; the #{w} is interpolation, just like in strings.

Sign up to request clarification or add additional context in comments.

2 Comments

@cary Swoveland perfect answer sir
This is so neat! very beautiful!

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.