简体   繁体   English

Ruby - 如何检查字符串是否包含数组中的所有单词?

[英]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"] 我有一系列的字符串: phrases = ["Have a good Thanksgiving", "Eat lots of food"]

I have another array of single words: words = ["eat", "food"] 我有另一个单词单词: 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? 我应该创建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? 函数迭代words数组的每个成员并进行比较,还是有任何我缺少的内置方法?

You're actually very close to the solution. 你实际上非常接近解决方案。

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

The all? all? method is on Enumerable , and returns true if the block evaluates to true for each item in the collection. 方法在Enumerable ,如果块对集合中的每个项的计算结果为true,则返回true。

Depending on exactly what your definition of the phrase "including" the word is, you may want to define your own include_all? 根据您对“包括”这个词的短语的定义,您可能想要定义自己的include_all? method, or a method on String to determine the match. 方法或String上的方法来确定匹配。 The include? 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? 如果这些不是您的要求,您可以使用Regexp代替include? or define your own method to wrap that logic up. 或定义自己的方法来包装该逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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