How to extract the sign of an integer in Ruby?

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

    You could use Kernel#sprintf to format numbers:

    def sign(i)
      sprintf("%+d", i)[0]
    end
    
    sign(100)  #=> "+"
    sign(-100) #=> "-"
    

提交回复
热议问题