How to extract the sign of an integer in Ruby?

Viewed 8025

I need a function which returns/prints the sign on an integer. So far I came up with this:

def extract_sign(integer)
  integer >= 0 ? '+' : '-'
end

Is there a built-in Ruby method which does that?

7 Answers
def sgn(x)
 [0,1,-1][x<=>0];
end

This return 0 if x==0, 1 if x>0 and -1 if x<0 without manipulating strings.

example:

sgn(2.0)*2**2

Related