In Ruby, you can negate a number (i.e. convert a positive number to negative, and a negative to positive) in the following ways:
Using Unary Minus Operator
You may negate a number using the unary minus operator (-) like so:
-n
This would convert a positive number to a negative number, and a negative number to a positive number. For example, you can use this in the following way:
def negate(num)
-num
end
puts negate(1234) #=> -1234
puts negate(-1234) #=> 1234
0 is a special case, which would always return 0 when negated:
# ... puts negate(0) #=> 0 puts negate(-0) #=> 0
Using Arithmetic Operators
You may convert a positive number to negative or vice versa by simply multiplying it by -1:
n * -1
Similarly, you may divide the number by -1 to achieve the same:
n / -1
Alternatively, you may subtract the number from 0:
0 - n
You could use any of these to convert a positive number to a negative number and vice versa, for example, like so:
def negate(num)
num * -1
end
puts negate(1234) #=> -1234
puts negate(-1234) #=> 1234
def negate(num)
num / -1
end
puts negate(1234) #=> -1234
puts negate(-1234) #=> 1234
def negate(num)
0 - num
end
puts negate(1234) #=> -1234
puts negate(-1234) #=> 1234
In any case, 0 would always return 0 when negated:
# ... puts negate(0) #=> 0 puts negate(-0) #=> 0
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.