Ruby - method_missing

8vius picture 8vius · Mar 11, 2012 · Viewed 10.8k times · Source

I'm trying to implement a method_missing for converting $ to other currencies, as in doing 5.dollars yields 5, 5.yen would yield 0.065 5.euro 6.56 and so on. This I can do now. Now I need to implement it but doing 5.dollars.in(:yen) for example.

This is what I have right now:

class Numeric
  @@currencies = {'yen' => 0.013, 'euro' => 1.292, 'rupee' => 0.019}
  def method_missing(method_id)
    singular_currency = method_id.to_s.gsub( /s$/, '')
    if @@currencies.has_key?(singular_currency)
      self * @@currencies[singular_currency]
    else
      super
    end
  end
end

Can anyone explain how I can do this?

PS: I'd rather you not give me the code, but an explanation, so I can determine on my own how it is done.

Answer

ubuntus picture ubuntus · Mar 13, 2012

Added currency 'dollar' and in method:

class Numeric
  @@currencies = {'dollar' => 1, 'yen' => 0.013, 'euro' => 1.292, 'rupee' => 0.019}
  def method_missing(method_id)
    singular_currency = method_id.to_s.gsub(/s$/, '')
    if @@currencies.has_key?(singular_currency)
      self * @@currencies[singular_currency]
    else
      super
    end
  end

  def in(currency)
    singular_currency = currency.to_s.gsub(/s$/, '')
    self / @@currencies[singular_currency]
  end
end