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 already implements a round method for Float. There is no need for your implementation.

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 に答える