4

我有一个字符串,例如:

'This is a test string'

和一个数组:

['test', 'is']

我需要找出数组中有多少元素存在于字符串中(在这种情况下,它将是 2)。这样做的最佳/红宝石方式是什么?另外,我这样做了数千次,所以请记住效率。

到目前为止我尝试了什么:

array.each do |el|
 string.include? el #increment counter
end

谢谢

4

5 回答 5

6
['test', 'is'].count{ |s| /\b#{s}\b/ =~ 'This is a test string' }

编辑:针对全词匹配进行了调整。

于 2012-10-12T13:39:47.373 回答
3
['test', 'is'].count { |e| 'This is a test string'.split.include? e }
于 2012-10-12T13:44:00.320 回答
2

你的问题模棱两可。

如果您正在计算出现次数,那么:

('This is a test string'.scan(/\w+/).map(&:downcase) & ['test', 'is']).length

如果您正在计算代币,那么:

(['test', 'is'] & 'This is a test string'.scan(/\w+/).map(&:downcase)).length

Array#&您可以通过使用Hash( 或)替换某些操作来进一步加快计算速度Set

于 2012-10-12T13:47:57.653 回答
0

凯尔的回答为您提供了简单实用的工作方式。但是,请允许我指出,当 n(字符串长度和/或匹配字符串的数量)攀升至数百万时,存在更有效的算法来解决您的问题。我们在生物学中经常遇到这样的问题

于 2012-10-12T13:44:45.233 回答
0

如果字符串或数组中没有重复项,以下将起作用。

str = "This is a test string"
arr = ["test", "is"]

match_count = arr.size - (arr - str.split).size # 2 in this example
于 2012-10-12T14:00:48.773 回答