How to extract the sign of an integer in Ruby?

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

    Here is a simple way to do it:

    x = -3
    "++-"[x <=> 0] # => "-"
    
    x = 0
    "++-"[x <=> 0] # => "+"
    
    x = 3
    "++-"[x <=> 0] # => "+"
    

    or

    x = -3
    "±+-"[x <=> 0] # => "-"
    
    x = 0
    "±+-"[x <=> 0] # => "±"
    
    x = 3
    "±+-"[x <=> 0] # => "+"
    

提交回复
热议问题