0014 Nonzero

The opposite of zero?... Well, not exactly!

A question mark doesn’t necessarily mean a Boolean return value. nonzero? is one of the few exceptions to this rule.

0014-nonzero_1.png

It returns nil if 0, otherwise self. So, in a way, yes, they are opposite methods. No difference if you use them in a condition.

0014-nonzero_2.png

But no, this distinction allows a completely different use of the nonzero? method. And that’s why it was created in the first place. In this thread Numeric#nonzero? behavior wanting to remove the ?, note 14 traces its (very interesting) history. To cut a long story short, it was to consider 0 as a false value for this particular case:

0014-nonzero_3.png

Although we can now compare arrays, nonzero? remains interesting because it allows a short-circuit.

Link to Ruby documentation for nonzero?.