我想更改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
但我得到一个错误,说我无法改变自我的价值。
有什么想法吗?
答案 0 :(得分:11)
您无法更改self
的值。它总是指向当前对象,你不能指向别的东西。
如果要改变对象的值,可以通过调用其他变异方法或设置或更改实例变量的值来实现,而不是尝试重新分配self
。但是在这种情况下,这对你没有帮助,因为Float
没有任何变异方法,并且设置实例变量不会给你任何东西,因为任何实例变量都不会影响任何默认的float操作
所以底线是:你不能在浮点数上写变异方法,至少不是你想要的方式。
答案 1 :(得分:1)
您还可以创建一个类并将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
有关使用“类变量”here的更多信息。
答案 2 :(得分:0)
这实际上是一个非常好的问题,我很遗憾地说你不能 - 至少不能使用Float
课程。这是不可改变的。我的建议是创建自己的类实现Float(也称继承所有方法),就像在伪代码中一样
class MyFloat < Float
static CURRENT_FLOAT
def do_something
CURRENT_FLOAT = (a new float with modifications)
end
end