Skip to content

Latest commit

 

History

History
40 lines (34 loc) · 702 Bytes

8 kyu - Return Negative.md

File metadata and controls

40 lines (34 loc) · 702 Bytes

Task

In this simple assignment you are given a number and have to make it negative. But maybe the number is already negative?

Example:

makeNegative(1); # return -1 makeNegative(-5); # return -5 makeNegative(0); # return 0 Notes:

The number can be negative already, in which case no change is required. Zero (0) is not checked for any specific sign. Negative zeros make no mathematical sense.

My solution

def makeNegative(num)
  if num > 0
    return -num
  elsif
    num < 0
    return num
  else
    0
  end
end

Much better solution

def makeNegative(num)
  -num.abs
end

Better if statement (Ternary)

# def makeNegative(num)
  num > 0 ? -num : num
end