3

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.

1
  • 1
    if bw.any? { |word| @nick =~ /#{word}/} should work. Example Commented Apr 29, 2015 at 13:20

2 Answers 2

2

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 
Sign up to request clarification or add additional context in comments.

4 Comments

@nick.include?(word) could be written shorter as @nick[word]. Not sure if this is really an improvement, though.
@undur_gongor : thanks for your point for shorter trick. I have updated my answer :)
I assume, the regexp version is only faster if you can build it once and query it often. I just tried and (at least for small lists) the regexp creation is far more expensive than iterating through the array. In addition, you may have to think about escaping special characters as in mudasobwa's answer.
@undur_gongor yes, regexes are built into a slightly optimized form that takes some more time for building, but results in faster checks.
2
@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.

3 Comments

this is a much better solution and other than Regexp.escape I just added it as a suggestion in my comment below.
I fail to see the benefit of a regexp here (in the second solution).
@undur_gongor Frankly, me too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.