Ruby-ArgumentError:参数数量错误(2对1)



我有以下类覆盖:

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

只要in的自变量是复数,例如:10.dollars.in(:yens),我得到ArgumentError: wrong number of arguments (2 for 1),但10.dollars.in(:yen)不会产生错误。知道为什么吗?

您犯了一个拼写错误:destination_currenydestination_currency不同。因此,当货币是复数时,您的@@currencies.has_key?测试失败,因为它是查看原始符号(destination_currency)而不是单个符号(destination_curreny)。这将通过super调用触发具有两个参数(method_iddestination_currency)的method_missing调用,但您已声明method_missing接受一个参数。这就是为什么您忽略了完整引用的错误消息是抱怨method_missing而不是in

修复你的打字错误:

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

您编写了

def in(destination_currency)

在Ruby中,这意味着in方法只接受一个参数。传递更多参数会导致错误。

如果你想让它有一个可变数量的参数,用splat操作符做这样的事情:

def in(*args)

相关内容

最新更新