Alex Popov Alex Popov - 6 months ago 10
Ruby Question

How to extract the sign of an integer in Ruby?

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


Is there a built-in Ruby method which does that?

Answer

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