How to extract the sign of an integer in Ruby? How to extract the sign of an integer in Ruby? ruby ruby

How to extract the sign of an integer in Ruby?


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] # => "+"


I think that it's nonsense not to have a method that just gives -1 or +1. Even BASIC has such a function SGN(n). Why should we have to deal with Strings when it's numbers we want to work with. But's that's just MHO.

def sgn(n)  n <=> 0end.


You could use Kernel#sprintf to format numbers:

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