2012-03-09 67 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