使用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)
我環顧四周,我有點明白是怎麼回事,但我不知道如何解決它。
哪一行拋出的錯誤? – DiegoSalazar
您正在將一個實例變量添加到一個Numeric實例。你不能這樣做 – levinalex
首先,不要將代碼與錯誤消息混合在一起。至少評論第一行。 –