Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
数组中字符串中匹配项的Ruby计数_Ruby - Fatal编程技术网

数组中字符串中匹配项的Ruby计数

数组中字符串中匹配项的Ruby计数,ruby,Ruby,我有一个字符串,例如: 'This is a test string' 和一个数组: ['test', 'is'] 我需要找出数组中有多少个元素以字符串的形式存在(在本例中为2)。最好的/ruby方法是什么?此外,我做这数千次,所以请记住效率 到目前为止,我尝试的是: array.each do |el| string.include? el #increment counter end 谢谢 编辑:调整为全词匹配。凯尔的回答为您提供了简单实用的方法。但是,请允许我指出,当n(字符串长度

我有一个字符串,例如:

'This is a test string'
和一个数组:

['test', 'is']
我需要找出数组中有多少个元素以字符串的形式存在(在本例中为2)。最好的/ruby方法是什么?此外,我做这数千次,所以请记住效率

到目前为止,我尝试的是:

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


编辑:调整为全词匹配。

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

你的问题模棱两可

['test', 'is'].count { |e| 'This is a test string'.split.include? e }
如果正在计算发生次数,则:

('This is a test string'.scan(/\w+/).map(&:downcase) & ['test', 'is']).length
如果您正在计算代币,则:

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

通过使用
散列
(或
)的某些操作替换
数组#和
,可以进一步加快计算速度。

如果字符串或数组中没有重复项,则可以执行以下操作

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

match_count = arr.size - (arr - str.split).size # 2 in this example

@SergioTulentsev I在数组中循环并使用include?方法:你认为什么是比赛?例如,你是计算“is”与单词“This”的匹配,还是只计算完整的单词匹配?这是
['test','is']。count{e |'这是一个测试字符串。包括?e}
,如果你想继续下去:)几乎,他使用regex来计算单词。这就是我发现这些算法效率相当低的原因,正则表达式比#include更多?多样性,但这对小n没有影响。OP正在尝试查找完整的单词出现,而
String#include?
对此不起作用<代码>'hello'。包括?('hell')#=>true@megas Yes。我真的是在评论Boris的“regex多于#include”评论。虽然你的回答非常有趣,但问题是它是否足够笼统。如果某些匹配字符串与同一个单词匹配(现在不是这样,但可能是一般情况),会发生什么情况?@BorisStitnicky我想你在问题中认识到了与我一样的模糊性。看我的编辑。是的,我从没说过是你的错。但我必须承认,这个问题是我今天手头无聊编程任务的一个有趣的补充:)@0xSina不客气。测试
str = "This is a test string"
arr = ["test", "is"]

match_count = arr.size - (arr - str.split).size # 2 in this example