Question

I have the following class overwrite:

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$/, '').to_sym
    if @@currencies.has_key?(singular_currency)
      self * @@currencies[singular_currency]
    else
      super
    end
  end

  def in(destination_currency)
    destination_curreny = destination_currency.to_s.gsub(/s$/, '').to_sym
    if @@currencies.has_key?(destination_currency)
      self / @@currencies[destination_currency]
    else
      super 
    end
  end
end

Whenever the argument for in is plural for example : 10.dollars.in(:yens) I get ArgumentError: wrong number of arguments (2 for 1) but 10.dollars.in(:yen) yields no error. Any idea why?

Was it helpful?

Solution

Your made a typo: destination_curreny is not the same as destination_currency. So when the currency is plural, your @@currencies.has_key? test fails because it is look at the original symbol (destination_currency) rather than the singularized symbol (destination_curreny). That will trigger a method_missing call with two arguments (method_id and destination_currency) through the super call but you've declared your method_missing to take one argument. That's why the error message that you neglected to fully quote is complaining about method_missing rather than in.

Fix your typo:

def in(destination_currency)
  destination_currency = destination_currency.to_s.gsub(/s$/, '').to_sym
  #...

OTHER TIPS

You wrote

def in(destination_currency)

In Ruby this means that your in method takes exactly one argument. Passing more arguments causes an error.

If you want to let it have a variable number of arguments do something like this with the splat operator:

def in(*args)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top