2012-03-11 72 views
0

我有下面的类覆盖:红宝石 - 引发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 

每当在参数是复数,例如:10.dollars.in(:yens)我得到ArgumentError: wrong number of arguments (2 for 1)10.dollars.in(:yen)产生任何错误。任何想法为什么?

+0

这个问题是题外话,因为它们只会让我们关闭错字/语法相关的问题这样 – random 2013-07-07 12:44:27

回答

5

你做了一个错字:destination_curreny是不一样的destination_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 
    #... 
+0

该死的错字,谢谢花花公子 – 8vius 2012-03-11 06:17:20

+5

@ 8vius:这个家伙守法。 – 2012-03-11 06:21:23

0

你写

def in(destination_currency) 

在Ruby中,这意味着你的in方法到底需要一个参数。传递更多参数会导致错误。

如果你想让它具有可变数量的参数,这样做与图示操作:

def in(*args) 
+0

我不明白,我怎么通过它多ARGS ? – 8vius 2012-03-11 06:11:02