Reputation: 23
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.
Upvotes: 2
Views: 198
Reputation: 10056
class String
def is_number?
Float(self) >= 0 rescue false
end
end
Upvotes: 5
Reputation: 230286
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
Upvotes: 1