9

I want to check if any elements in this array words = ["foo", "bar", "spooky", "rick james"] are substrings of the phrase sentence = "something spooky this way comes".

Return true if there is any match, false if not.

My current solution (works but probably inefficient, I'm still learning Ruby):

is_there_a_substring = false
words.each do |word|
  if sentence.includes?(word)
    is_there_a_substring = true
    break
  end
end
return is_there_a_substring

2 Answers 2

23

Your solution is efficient, it's just not as expressive as Ruby allows you to be. Ruby provides the Enumerable#any? method to express what you are doing with that loop:

words.any? { |word| sentence.include?(word) }
Sign up to request clarification or add additional context in comments.

3 Comments

gotta love ruby... (will accept in 4 min when timer is up)
use include? as includes? doesn't work for me in ruby2.0
There is no includes? in Ruby. This answer needs to be edited to use include?
5

Another option is to use a regular expression:

 if Regexp.union(words) =~ sentence
   # ...
 end

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.