Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
nonzero
number
communitycreator

What is number.nonzero? in Ruby?

okwudili onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

.nonzero? or nonzero?() is a Ruby function that is called on a number to check if the number is non-zero.

The function returns the number if the number is truly non-zero. Otherwise, it returns nil or nothing.

Syntax

number.nonzero?
# OR
number.nonzero?()

Parameters

The function needs no parameters. It is only called on a number value.

Return value

If the number is non-zero, it returns the number itself. Otherwise, it returns nothing or nil.

Code

In the code example, non-zero numbers have the nonzero? method called on them and the value returned is printed to the console.

# all these non-zero numbers get printed!
puts 12.nonzero?
puts 1.nonzero?
puts 1_200.nonzero? # same as 1200
puts 600.nonzero?
puts 90/90*3+5.nonzero?
puts 1.nonzero?
puts 0.3.nonzero?
puts -0.9.nonzero?
puts -4.9.nonzero?
puts 0.nonzero?() # returns nil

It is important to note that when .nonzero? is called on numbers that are actually zero, nothing is printed. See example below:

# Nothing is printed for a zero number
puts 0.nonzero?

RELATED TAGS

ruby
nonzero
number
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring