Q:

Ruby: why does =~ evaluate to true in an if statement?

I'm learning Ruby and have seen (and using) regex matching in this way:
a = "string9"
if a =~ /\d/
  #do something
end

The code would work but today I read the documentation on Regex and learned that =~ returns the position of the match in the string, nil if no match. I thought =~ returns true or false when it is the === that returns true for match, and false for no match. It seems the if statement in the above code should be rewritten:
if /\d/ === a

I have tried both and the program would run without error. I'm just trying to understand what's going on. It seems "if" will take anything but "nil" as true. I guess my question is less about regex but more about how the if statement (and other boolean statements) works.

A:

The predicate after if will be treated as a boolean value.
In Ruby, only false and nil are treated as false. Anything other will be evaluated to true, so 0, [], {} are all true in boolean context.
From Ruby doc:

nil and false are both false values. nil is sometimes used to indicate "no value" or "unknown" but evaluates to false in conditional expressions.
true is a true value. All objects except nil and false evaluate to a true value in conditional expressions.

And you may have a look at the control expressions.

