Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a string contains any substrings from an array

Tags:

ruby

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
like image 248
Don P Avatar asked Apr 27 '14 05:04

Don P


2 Answers

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) }
like image 89
Paige Ruten Avatar answered Oct 14 '22 03:10

Paige Ruten


Another option is to use a regular expression:

 if Regexp.union(words) =~ sentence
   # ...
 end
like image 41
Stefan Avatar answered Oct 14 '22 02:10

Stefan