문제

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.

도움이 되었습니까?

해결책

class String
  def is_number?
    Float(self) >= 0 rescue false
  end
end

다른 팁

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top