看看这个(用更少草率的代码编辑)
class Numeric
@@currencies = {'dollar' => 1, 'yen' => 0.013, 'euro' => 1.292, 'rupee' => 0.019}
attr_writer :previous_currency
def method_missing(method_id)
singular_currency = method_id.to_s.gsub( /s$/, '')
if @@currencies.has_key?(singular_currency)
@previous_currency = singular_currency
self * @@currencies[singular_currency]
else
super
end
end
def in(currency)
singular_currency = currency.to_s.gsub( /s$/, '')
rate = @@currencies[singular_currency]
if @@currencies[@previous_currency] < rate
self / rate
else
self * rate
end
end
end
Numeric 类的此扩展允许执行以下操作:
<Number>.<currency>.in(:<other_currency>)
喜欢5.dollars.in(:euros)
如果我有dollars第一个缺失的方法,它就可以了。@previous_currency在第一次拍摄时获取值dollar,然后在调用缺少的方法in时,它保留其值并进行转换就好了。但是如果我尝试其他方法而不是dollarsordollar,@previous_currency就会以某种方式失去它的价值,nil在调用时再次成为in,导致以下错误
NoMethodError: undefined method ` for nil:NilClass
我试图改变美元在@@currencies哈希中的位置,但同样的行为再次发生。
Ruby 更喜欢美元吗?