Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract the sign of an integer in Ruby?

Tags:

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?

like image 269
Alexander Popov Avatar asked Dec 12 '13 08:12

Alexander Popov


People also ask

How do you check if a value is an integer in Ruby?

The Number. isInteger() method returns true if a value is an integer of the datatype Number. Otherwise it returns false .

How do you get an integer from a string in Ruby?

Converting Strings to Numbers Ruby provides the to_i and to_f methods to convert strings to numbers. to_i converts a string to an integer, and to_f converts a string to a float.

How do I remove numbers from a string in Ruby?

string. gsub!( /\d+/,"") will remove all numbers from the string.


2 Answers

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] # => "+" 
like image 81
sawa Avatar answered Sep 22 '22 17:09

sawa


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. 
like image 23
Douglas G. Allen Avatar answered Sep 21 '22 17:09

Douglas G. Allen