2012-03-09 5 views
1

내가 근본적으로 원하는 것은 정의되지 않은 메소드가 [엔, 유로 등]이 호출 될 때 설정되는 하나의 추가 속성 (currencie)을 갖도록 Numeric 클래스를 확장하는 것입니다. 그래서, attri 또한루비. OOP. 속성이 저장되지 않았습니까?

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

: 내가있어

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

코드를 실행할 때

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 

지금 여기 클래스 정의는 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 

편집 : injekt로 고정이

+0

기다립니다, 이것은 잘못된 것입니다 말했다. 그렇지 않으면'puts' 위의 줄이 완전히 쓸모 없게됩니다. –

+0

감사합니다. 업데이트를 참조하십시오. – megas

+0

유감스럽게 생각합니다. 그러나 그것도 작동하지 않습니다. 숫자에서'self'의 값을 변경할 수 없습니다. 위의 코드 대신'self'를 반환하면됩니다. –

관련 문제