2012-03-09 68 views
1

我想要的是扩展Numeric类,以便它具有一个额外的Attribute(currencie),当未定义的方法被调用时设置[日元(s),欧元(s)等] 因此,这里是类定义:红宝石。 OOP。属性没有存储?

class Numeric 

@@currencies = {'yen' => 0.013, 'euro' => 1.292, 'rupee' => 0.019, 'dollar' => 1} 

attr_accessor :currencie 

def method_missing(method_id) 
    singular_currency = method_id.to_s.gsub(/s$/, '') 
    if @@currencies.has_key?(singular_currency) 
    self.currencie = singular_currency 
    self * @@currencies[singular_currency] 
    puts "method finished" 
    else 
    super 
    end 
end 

def in(convert_to) 

end 

end 

现在,当我运行的代码

a = 5.rupees 
puts "currencie is -> " + a.currencie 

我有:

method finished 
/path_to_file/hw2.1.rb:33:in `<main>': undefined method `currencie' for nil:NilClass (NoMethodError) 

另外,attri bute currencie似乎未设置。

我在做什么错了?

回答

1

在你的情况下,method_missing应返回对象,即self。只需将self添加到method_missing即可使用。

def method_missing(method_id) 
    singular_currency = method_id.to_s.gsub(/s$/, '') 
    if @@currencies.has_key?(singular_currency) 
    self.currencie = singular_currency   
    puts "method finished" 
    self * @@currencies[singular_currency] # just change the order of expressions 
    else 
    super 
    end 
end 

编辑:固定为injekt

+0

等待,这是错误的。你想返回'self * @@ currency [singular_currency]'不是未修改的'self'',否则这使得'puts'上面的行完全没用 – 2012-03-09 11:49:56

+0

谢谢,查看更新 – megas 2012-03-09 12:01:17

+0

对不起,很迂腐。但那也行不通。你不能在数字中改变'self'的值。您只需将上面的代码替换为返回“self”即可。 – 2012-03-09 12:04:10