Alex Popov - 1 year ago 41

Ruby Question

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 Source

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