From: "David A. Black" Date: 2008-04-30T23:14:57+09:00 Subject: Re: Search string for occurneces of words stored in array 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 Another possibility: irb(main):009:0> sentence = "This is my test sentence" => "This is my test sentence" irb(main):010:0> re = Regexp.new(words.join('|')) => /This|is|my/ irb(main):011:0> sentence =~ re => 0 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!