How to extract the sign of an integer in Ruby?

前端 未结 7 2109
渐次进展
渐次进展 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

提交回复
热议问题