Ruby和为Float实例修改self

我想改变float实例的自身值。

我有以下方法:

class Float def round_by(precision) (self * 10 ** precision).round.to_f / 10 ** precision end end 

我想添加round_by! 将修改自我值的方法。

 class Float def round_by!(precision) self = self.round_by(precision) end end 

但我得到一个错误,说我无法改变自我的价值。

任何的想法 ?

你无法改变self的价值。 它总是指向当前对象,你不能指向别的东西。

当您想要改变对象的值时,您可以通过调用其他变异方法或设置或更改实例变量的值来执行此操作,而不是尝试重新分配self 。 但是在这种情况下,这对你没有帮助,因为Float没有任何变异方法,并且设置实例变量不会给你任何东西,因为任何实例变量都不会影响任何默认的float操作。

所以底线是:你不能在浮点数上写变异方法,至少不是你想要的方式。

您还可以创建一个类并将float存储在实例变量中:

 class Variable def initialize value = nil @value = value end attr_accessor :value def method_missing *args, &blk @value.send(*args, &blk) end def to_s @value.to_s end def round_by(precision) (@value * 10 ** precision).round.to_f / 10 ** precision end def round_by!(precision) @value = round_by precision end end a = Variable.new 3.141592653 puts a #=> 3.141592653 a.round_by! 4 puts a #=> 3.1416 

有关在此处使用“类变量”的更多信息。

这实际上是一个非常好的问题,我很遗憾地说你不能 – 至少不能使用Float类。 这是不可改变的。 我的建议是创建自己的类实现Float(也称inheritance所有方法),就像在伪代码中一样

 class MyFloat < Float static CURRENT_FLOAT def do_something CURRENT_FLOAT = (a new float with modifications) end end