How to extract the sign of an integer in Ruby?
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 <=> 0
end.
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] # => "+"