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) }
3
  • gotta love ruby... (will accept in 4 min when timer is up)
    – Don P
    Commented Apr 27, 2014 at 5:20
  • 4
    use include? as includes? doesn't work for me in ruby2.0
    – Radek
    Commented Aug 13, 2015 at 2:23
  • 1
    There is no includes? in Ruby. This answer needs to be edited to use include?
    – JEMaddux
    Commented May 8, 2017 at 15:56
5

Another option is to use a regular expression:

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.