Skip to content

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

instance method

Numeric#nonzero?

num.nonzero? → self or nil

Returns self if num is not zero, nil otherwise.

This behavior is useful when chaining comparisons:

Example
a = %w( z Bb bB bb BB a aA Aa AA A )
b = a.sort {|a,b| (a.downcase <=> b.downcase).nonzero? || a <=> b }
b   #=> ["A", "a", "AA", "Aa", "aA", "BB", "Bb", "bB", "bb", "z"]
See also #negative? #numerator #modulo #phase also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.1