Skip to content

End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

Numeric#nonzero?

nonzero? → self or nil

Returns self if self is not a zero value, nil otherwise; uses method zero? for the evaluation.

The returned self allows the method to be chained:

Example
a = %w[z Bb bB bb BB a aA Aa AA A]
a.sort {|a, b| (a.downcase <=> b.downcase).nonzero? || a <=> b }
# => ["A", "a", "AA", "Aa", "aA", "BB", "Bb", "bB", "bb", "z"]

Of the Core and Standard Library classes, Integer, Float, Rational, and Complex use this implementation.

See also #negative? #numerator #modulo #phase also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.0