To make sure that you always return a negative number in Ruby, you can do either of the following:
#Using Unary Minus Operator
You can convert the number to its absolute form, and then negate it using the unary minus operator (-):
-n.abs
This would convert a positive number to negative and ensure that an already negative number remains unchanged. For example, you can use this in the following way:
def neg(num)
-num.abs
end
puts neg(1234) #=> -1234
puts neg(-1234) #=> -1234
#Using Arithmetic Operators
You can convert the number to its absolute form, and then negate it either by:
- Multiplying or dividing the number by
-1, or; - Subtracting the number from
0.
n.abs * -1
n.abs / -1
0 - n.abs
These would convert a positive number to negative and ensure that an already negative number remains unchanged. For example, you can use any of these in the following way:
def neg(num)
num.abs * -1
end
puts neg(1234) #=> -1234
puts neg(-1234) #=> -1234
def neg(num)
num.abs / -1
end
puts neg(1234) #=> -1234
puts neg(-1234) #=> -1234
def neg(num)
0 - num.abs
end
puts neg(1234) #=> -1234
puts neg(-1234) #=> -1234