How to extract the sign of an integer in Ruby?

前端 未结 7 2106
渐次进展
渐次进展 2020-12-30 00:49

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


        
相关标签:
7条回答
  • 2020-12-30 01:37
    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

    0 讨论(0)
提交回复
热议问题