Рубин.ООП.Атрибут не хранится? - PullRequest
1 голос
/ 09 марта 2012

То, что я в основном хочу, это расширить класс Numeric, чтобы у него был один дополнительный атрибут (currencycie), который устанавливается при вызове неопределенных методов [иен (ы), евро (с) и т. Д.]вот определение класса:

 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) 

Также атрибут currentcie кажется не установленным.

Что я делаю не так?

1 Ответ

1 голос
/ 09 марта 2012

В вашем случае 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 сказал

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...