Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby count # of matches in string from array

Tags:

ruby

I have a string, for example:

'This is a test string'

and an array:

['test', 'is']

I need to find out how many elements in array are present in string (in this case, it would be 2). What's the best/ruby-way of doing this? Also, I am doing this thousands of time, so please keep in mind efficiency.

What I tried so far:

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

Thanks

like image 221
0xSina Avatar asked Dec 20 '22 15:12

0xSina


1 Answers

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

Edit: adjusted for full word matching.

like image 85
Kyle Avatar answered Dec 30 '22 18:12

Kyle