2012-03-09 10 views
1

私が基本的に望むのは、未定義メソッドが呼び出されたときに設定される1つの追加の属性(currencie)を持つようにNumericクラスを拡張することです。 したがって、ここでは、クラス定義は次のとおりです。今Ruby。 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が返されます。 selfmethod_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 

EDIT:injekt

+0

これは間違っている、待って言ったように修正しました。 'self * @@ currency {singular_currency}'を変更しないで 'self'を返そうとします。そうしないと、' puts'の上の行はまったく役に立たなくなります。 –

+0

ありがとう、更新情報 – megas

+0

ごめんなさい。しかし、それはどちらもうまくいかないでしょう。 'self'の値を数値で変更することはできません。あなたは上記のコードの代わりに 'self'を返す必要があります。 –

関連する問題