Ruby: Change negative number to positive number?

RubyMathNumbers

Ruby Problem Overview


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

ie. Change "-300" to "300"

Ruby Solutions


Solution 1 - Ruby

Using abs will return the absolute value of a number

-300.abs  # 300
300.abs   # 300

Solution 2 - Ruby

Put a negative sign in front of it.

>> --300
=> 300
>> x = -300
=> -300
>> -x
=> 300

Solution 3 - Ruby

Wouldn't it just be easier to multiply it by negative one?

x * -1

That way you can go back and forth.

Solution 4 - Ruby

Most programming languages have the ABS method, however there are some that do not Whilst I have not used Ruby before, I am familiar its a framework that runs on PHP

The abs method is available on PHP https://www.php.net/manual/en/function.abs.php

With Ruby the syntax appears slightly different is integer.abs https://www.geeksforgeeks.org/ruby-integer-abs-function-with-example/

But for future reference the abs method is really small to code your self.

here is how in a few different languages:

JavaScript:

function my_abs(integer){
    if (integer < 0){
        return integer * -1;
    }
    return interger;
}

Python:

    def my_abs(integer):
    if (integer < 0):
        return integer * -1
    return integer

c:

int my_abs(int integer){
    if (interger < 0){
        return integer * -1;
    }
    return integer;
}

This means should you ever find yourself with a programming language that doesnt have a built in abs method, you know how to code your own its just simply multiply any negative number by -1 as you would of gathered in my examples

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShpigfordView Question on Stackoverflow
Solution 1 - RubyYacobyView Answer on Stackoverflow
Solution 2 - RubyBrandon BodnarView Answer on Stackoverflow
Solution 3 - Rubyabsynthe minded web smithView Answer on Stackoverflow
Solution 4 - RubyDataCureView Answer on Stackoverflow