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
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.
Ruby doesn't have a built in sign function like Javascript. Here's a thread that explains more http://www.ruby-forum.com/topic/141216
Your approach looks correct.
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 use n == 0 ? 1 : n.abs / n
, e.g.:
def sign(n)
n == 0 ? 1 : n.abs / n
end
sign(10) # 1
sign(0) # 1
sign(-5) # -1
You could use Kernel#sprintf to format numbers:
def sign(i)
sprintf("%+d", i)[0]
end
sign(100) #=> "+"
sign(-100) #=> "-"
class Numeric
def sign
if self > 0
'+'
elsif zero?
nil
else
'-'
end
end
end