class String
def is_number?
Float(self) >= 0 rescue false
end
end
is_numeric eliminating negative numbers in Ruby
-
30-03-2022 - |
Question
I'm a new user here and also beginner with Ruby. I need to eliminate the negative values (numbers) from is_numeric?
. So the code is this way:
class String
def is_number?
true if Float(self) rescue false
end
end
That gives me positive and negative numbers while I need to get only the positive numbers. Is there a way to eliminate negative numbers in this method? If not then any other way is also appreciated.
La solution
Autres conseils
Something like this should work:
class String
def is_number?
f = Float(self)
f && f >= 0
rescue
false
end
end
'1'.is_number? # => true
'-1'.is_number? # => false
'0.0'.is_number? # => true
'4.12'.is_number? # => true
'-10_000'.is_number? # => false
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow