2014-02-07 39 views
0

使用Ruby 2.0時,出現以下錯誤,我不知道如何解決該問題。Ruby運行時錯誤Frozen Fixnum

class Numeric 
    @@currencies = {'yen' => 0.013, 'euro' => 1.292, 'rupee' => 0.019, 'dollar' => 1} 
    def method_missing(method_id) 
    singular_currency = method_id.to_s.gsub(/s$/, '') 
    @src_currency = singular_currency 
    if @@currencies.has_key?(singular_currency) 
     self * @@currencies[singular_currency] 
    else 
     super 
    end 
    end 

    def in(dst_currency) 
    (1/@@currencies[dst_currency.to_s.gsub(/s$/, '')]) * self 
    end 
end 

p 5.dollars.in(:euros) 
p 10.euros.in(:rupees) 

這將引發一個錯誤:

`method_missing': can't modify frozen Fixnum (RuntimeError) 

我環顧四周,我有點明白是怎麼回事,但我不知道如何解決它。

+0

哪一行拋出的錯誤? – DiegoSalazar

+0

您正在將一個實例變量添加到一個Numeric實例。你不能這樣做 – levinalex

+0

首先,不要將代碼與錯誤消息混合在一起。至少評論第一行。 –

回答

0

問題出在線@src_currency = singular_currency。擺脫「@」,你應該很好去。

什麼錯誤味精告訴你的是,你試圖修改冷凍Fixnum對象(通過指定一個實例變量的話)

2

這是錯誤的一個簡單的例子:

class Numeric 
    def add_an_instance_variable 
    @foo = 1 
    end 
end 

5.add_an_instance_variable 

這是因爲Fixnum被凍結,你不允許修改它們。

這樣做的原因是,Fixnums are special

Fixnum objects have immediate value. This means that when they are assigned or passed as parameters, the actual object is passed, rather than a reference to that object.

Assignment does not alias Fixnum objects. There is effectively only one Fixnum object instance for any given integer value, so, for example, you cannot add a singleton method to a Fixnum. Any attempt to add a singleton method to a Fixnum object will raise a TypeError.

直接對象進行了詳細解釋了Programming Ruby Book


如果你希望你的數字存儲他們在你什麼貨幣」我們需要將它們包裝在自己的班級中。

(不重新發明Money Gem。這是很好的。你也許可以用它)