The number of Ruby rows in a row from an array

I have a line like:

'This is a test string' 

and array:

 ['test', 'is'] 

I need to find out how many elements in the array are present in the string (in this case it will be 2). What is the best / ruby ​​way to do this? In addition, I do it thousands of times, so please keep in mind the effectiveness.

What I have tried so far:

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

thanks

+4
source share
5 answers
 ['test', 'is'].count{ |s| /\b#{s}\b/ =~ 'This is a test string' } 

Edit:, adjusted for full word matching.

+6
source

Your question is ambiguous.

If you count occurrences, then:

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

If you are counting tokens, then:

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

You can speed up the calculation by replacing Array#& with some operation using Hash (or Set ).

+2
source
 ['test', 'is'].count { |e| 'This is a test string'.split.include? e } 
+1
source

Kyle's answer gave you a simple practical way to do the job. But looking at this, let me say that there are more efficient algorithms to solve your problem when n (the length of the string and / or the number of matching strings) goes up by millions. We usually encounter such problems in biology .

0
source

The following will work if there are no duplicates in the row or array.

 str = "This is a test string" arr = ["test", "is"] match_count = arr.size - (arr - str.split).size # 2 in this example 
0
source

Source: https://habr.com/ru/post/1439392/


All Articles