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)
 ##
end

      

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

+3


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 

      

+2


source


@nick =~ Regexp.new(bw.map { |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[Regexp.new(Regexp.escape(w))] }

      

Hope it helps.

+2


source







All Articles