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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With