Expanding on Clint Pachl's answer:
Regex matching in Ruby returns nilnil
when the expression doesn't match. When it does, it returns the index of the character where the match happens. For example:
"foobar" =~ /bar/ # returns 3
"foobar" =~ /foo/ # returns 0
"foobar" =~ /zzz/ # returns nil
It's important to note that in Ruby only nilnil
and the boolean expression falsefalse
evaluate to false. Everything else, including an empty arrayArray, empty hashHash, or the integerInteger 0, evaluates to true.
That's why the /foo//foo/
example above works, and why.
if "string" =~ /regex/
works as expected. Only, only entering the 'true' part of the ifif
block if a match occurred.