我在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
如何使此覆盖工作?
答案 0 :(得分:3)
Ruby已经为round
实现了Float
方法。您无需执行。
0.12345.round(2) # => 0.12
0.12345.round(3) # => 0.123
答案 1 :(得分: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)
编辑:几乎忘记了你还需要确保在应用启动时将其全部包含在内。