tags:

views:

584

answers:

2

What's the simplest way of changing a negative number to positive with ruby?

ie. Change "-300" to "300"

+8  A: 

Using abs will return the absolute value of a number

-300.abs  # 300
300.abs   # 300
Yacoby
my answer is just for negative numbers, if you need to always have the absolute value then this is definitely the better way.
Brandon Bodnár
Yacoby, perfect. Just what I needed.
Shpigford
+2  A: 

Put a negative sign in front of it.

>> --300
=> 300
>> x = -300
=> -300
>> -x
=> 300
Brandon Bodnár
Just note that if the number is already positive, this will make it negative.
musicfreak
Yeah. Clarified that in my comment to the above accepted answer.
Brandon Bodnár