Jack
Jack

Reputation: 33

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

I have an array of banned words in Ruby:

bw = ["test"]

I want to check @nick against it.

For example

@nick = 'justatest'

would match.

I have tried:

if @nick.include?(bw)
 ##
end

but that doesn't seem to be the right way to do it as it doesn't catch it.

Upvotes: 3

Views: 185

Answers (2)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

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

Here we join all strings in bw into one regular expression, escaping possible symbols that have special meaning in a regular expression and check the input against it.

Another way to achieve this functionality is to check for every blacklisted word separately:

bw.any? { |w| @nick[Regexp.new(Regexp.escape(w))] }

Hope it helps.

Upvotes: 2

Gagan Gami
Gagan Gami

Reputation: 10251

If your concern is to check only (as your question's title suggests) then:

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

Though it might be faster to convert the array of strings into a Regexp:

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

Upvotes: 2

Related Questions