Home > Blockchain >  Change positive to negative number in Ruby?
Change positive to negative number in Ruby?

Time:05-17

I'm very new to Ruby. Apologies if this topic has already been covered (I see switching neg to pos but not the other way around).

I am entering this in Codewars but getting an error message:

def make_negative(num) 
  if num <= 0 return num 
  else return num(*-1)
end

What am I doing wrong?

CodePudding user response:

An alternative with a single branch: abs plus unary minus

def make_negative(num) 
  -num.abs
end

CodePudding user response:

You are missing an end for the if...else block. Furthermore, num(*-1) is raising an error because num isn't a method accepting arguments but a variable, and *-1 isn't a valid Ruby expression.

This should work:

def make_negative(num) 
  if num <= 0 
    return num 
  else 
    return num * -1
  end
end

CodePudding user response:

Something like this should be fine:

def make_negative(num)
  return num <= 0 ? num : num * -1
end

You have brackets around the (*-1) but you should be using num * -1.

  •  Tags:  
  • ruby
  • Related