2011-01-09 70 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的更多信息。