zoetropo
zoetropo

Reputation: 1

Change positive to negative number in Ruby?

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?

Upvotes: 0

Views: 588

Answers (3)

spickermann
spickermann

Reputation: 106792

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

Upvotes: 1

Ursus
Ursus

Reputation: 30056

An alternative with a single branch: abs plus unary minus

def make_negative(num) 
  -num.abs
end

Upvotes: 3

James
James

Reputation: 1

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.

Upvotes: 0

Related Questions