How to check if a string contains part of an array in Ruby?

I have an array of forbidden words in Ruby:

bw = ["test"]


I want to check @nick

on it.

for example

@nick = 'justatest'

will match.

I tried:

if @nick.include?(bw)


but that doesn't seem like the correct way to do it as it won't catch it.


source to share

2 answers

If your problem is to check only (as the question title suggests) then do the following:

> bw.any? { |word| @nick[word] }
=> true 


Although it might be faster to convert an array of strings to Regexp:

> bw = ["test", "just", "gagan"]
> g = /#{bw.join("|")}/
> g === @nick 
 => true 




@nick =~ { |w| Regexp.escape(w) }.join('|'))


Here we concatenate all strings into bw

a single regex, avoiding possible characters that have special meaning in the regex and validating the input against it.

Another way to achieve this functionality is to check every single word on the blacklist:

bw.any? { |w| @nick[] }


Hope it helps.



All Articles