0

我在 lib 文件夹中创建了 Float 类:

class Float
  def precision(p = 2)
    # Make sure the precision level is actually an integer and > 0
    raise ArgumentError, "#{p} is an invalid precision level. Valid ranges are integers > 0." unless p.class == Fixnum or p < 0
    # Special case for 0 precision so it returns a Fixnum and thus doesn't have a trailing .0
    return self.round if p == 0
    # Standard case
    (self * 10**p).round.to_f / 10**p
  end
end

在 rspec 测试中,有效。但是当应用程序运行时,会引发此错误:

undefined method `precision' for 5128.5:Float

如何使这个覆盖工作?

4

2 回答 2

3

Ruby 已经roundFloat. 不需要您的实施。

0.12345.round(2) # => 0.12
0.12345.round(3) # => 0.123 
于 2012-07-08T21:16:07.450 回答
0

我认为应该这样做。

module MyFloatMod
  def precision(p = 2)
    # Make sure the precision level is actually an integer and > 0
    raise ArgumentError, "#{p} is an invalid precision level. Valid ranges are integers > 0." unless p.class == Fixnum or p < 0
    # Special case for 0 precision so it returns a Fixnum and thus doesn't have a trailing .0
    return self.round if p == 0
    # Standard case
    (self * 10**p).round.to_f / 10**p
  end
end

Float.send(:include, MyFloatMod)

编辑:几乎忘记了您还需要确保在您的应用程序启动期间将所有这些都包含在某个地方。

于 2012-07-08T22:47:48.690 回答