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?
The Number. isInteger() method returns true if a value is an integer of the datatype Number. Otherwise it returns false .
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.
string. gsub!( /\d+/,"") will remove all numbers from the string.
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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With