我在 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
如何使这个覆盖工作?