Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - How to check if a string contains all the words in an array?

Tags:

string

ruby

I have an array of strings: phrases = ["Have a good Thanksgiving", "Eat lots of food"]

I have another array of single words: words = ["eat", "food"]

I want to return the entries in the first array if the string contains all the words in the second array.

So, it should look something like this:
phrases.select{ |x| x.include_all?(words) }

Should I just create the include_all? function to iterate through each member of the words array and do the comparison, or is there any built-in methods I'm missing?

like image 982
johnnycakes Avatar asked Nov 07 '11 20:11

johnnycakes


1 Answers

You're actually very close to the solution.

phrases.select do |phrase|
  words.all?{ |word| phrase.include? word }
end

The all? method is on Enumerable, and returns true if the block evaluates to true for each item in the collection.

Depending on exactly what your definition of the phrase "including" the word is, you may want to define your own include_all? method, or a method on String to determine the match. The include? method is case-sensitive and doesn't care about word boundaries. If those aren't your requirements, you can use a Regexp in place of include? or define your own method to wrap that logic up.

like image 179
Emily Avatar answered Sep 20 '22 21:09

Emily