From: "David A. Black" Date: 2008-05-01T07:23:52+09:00 Subject: Re: Search string for occurneces of words stored in array Hi -- On Wed, 30 Apr 2008, David A. Black wrote: > Hi -- > > On Wed, 30 Apr 2008, John Butler wrote: > >> Hi, >> >> I have a sentence "This is my test sentence" and an array["is", "the", >> "my"] and what i need to do is find the occurence of any of thearray >> words in the sentence. >> >> I have this working in a loop but i was wondering is there a way to do >> it using one of rubys string methods. >> >> Its sililar to the include method but searching for multiple words not >> just one. >> >> "This is my test sentence".include?("This") returns true >> >> but i want something like >> >> "This is my test sentence".include?("This", "is", "my") >> >> anyone got a nice way to do this? I only need to find if one of the >> words occure and then i exit. > > > You could use any? > > irb(main):001:0> words = %w{ This is my } > => ["This", "is", "my"] > irb(main):002:0> sentence = "This is my test sentence" > => "This is my test sentence" > irb(main):003:0> words.any? {|word| sentence.include?(word) } > => true > irb(main):004:0> sentence = "Hi" > => "Hi" > irb(main):005:0> words.any? {|word| sentence.include?(word) } > => false Actually, sentence.include?(word) isn't good, because it will give false positives (for substrings). David -- Rails training from David A. Black and Ruby Power and Light: INTRO TO RAILS June 9-12 Berlin ADVANCING WITH RAILS June 16-19 Berlin INTRO TO RAILS June 24-27 London (Skills Matter) See http://www.rubypal.com for details and updates!