2011-01-09 67 views
8

我想改变一个浮点实例的自我价值。Ruby和修改自己的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 

但是我得到一个错误,说我不能改变自我的价值。

有什么想法?

+2

你能想象如果调用`x = 13.2; x.round!`导致应用程序中所有`13.2`的值都变为`13`?这将是多么不幸。 – Phrogz 2011-01-10 01:43:38

回答

10

您不能更改self的值。它总是指向当前的对象,你不能指向其他的东西。

如果要变更对象的值,可以通过调用其他变异方法或设置或更改实例变量的值来完成此操作,而不是尝试重新指定self。然而,在这种情况下,这不会对您有所帮助,因为Float没有任何变异方法,并且设置实例变量不会为您购买任何东西,因为没有任何默认浮点操作受到任何实例变量的影响。

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

0

这实际上是一个非常好的问题,我很抱歉地说你不能 - 至少不能用Float这个课。它是不可变的。我的建议是要创建自己的类的农具浮法(又名继承了所有的方法),像这样的伪代码

class MyFloat < Float 
    static CURRENT_FLOAT 

    def do_something 
    CURRENT_FLOAT = (a new float with modifications) 
    end 
end 
+0

感谢您的诀窍! – Arkan 2011-01-09 18:31:35

1

您也可以在一个实例变量创建一个类,存储浮动:

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的更多信息。