【问题标题】:is_numeric eliminating negative numbers in Rubyis_numeric 消除 Ruby 中的负数
【发布时间】:2013-03-29 12:24:16
【问题描述】:

我是这里的新用户,也是 Ruby 的初学者。我需要从is_numeric? 中消除负值(数字)。所以代码是这样的:

class String
  def is_number?
    true if Float(self) rescue false
  end
end

这给了我正数和负数,而我只需要得到正数。有没有办法在这种方法中消除负数?如果没有,那么任何其他方式也值得赞赏。

【问题讨论】:

    标签: ruby numeric negative-number


    【解决方案1】:
    class String
      def is_number?
        Float(self) >= 0 rescue false
      end
    end
    

    【讨论】:

    • 出于好奇,你为什么写Float(self)这行?这条线的必要性是什么?
    • @iAmRubuuu: Float 如果字符串无法转换为数字,函数会引发错误。
    【解决方案2】:

    这样的事情应该可以工作:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多