简体   繁体   中英

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

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM