How to Convert Positive Numbers to Negative in Ruby?

In Ruby, you can convert a positive number to negative in the following ways:

If you wish to always return a negative number (i.e. retain the sign of a negative number whilst ensuring that any positive number is converted to negative), then you can first convert the number to its absolute form, and then negate it.

Using Unary Minus Operator

You may convert a positive number to negative by using the unary minus operator (-) like so:

-n

For example, you can use this in the following way:

num = 1234
negated = -num

puts negated #=> -1234

Using Arithmetic Operators

You can convert a positive number to negative by simply multiplying or dividing it by -1:

n * -1
n / -1

Alternatively, you may subtract the number from 0:

0 - n

You can use any of these to convert a positive number to a negative number, for example, like so:

num = 1234
negated = num * -1

puts negated #=> -1234
num = 1234
negated = num / -1

puts negated #=> -1234
num = 1234
negated = 0 - num

puts negated #=> -1234

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.