[英]Ruby - ArgumentError: wrong number of arguments (2 for 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)
: 10.dollars.in(:yens)
我都會得到ArgumentError: wrong number of arguments (2 for 1)
但是10.dollars.in(:yen)
不會產生錯誤。 知道為什么嗎?
您打錯了: destination_curreny
與destination_currency
。 因此,當貨幣為復數時,您的@@currencies.has_key?
測試失敗,因為它查看的是原始符號( destination_currency
)而不是單數符號( destination_curreny
)。 這將通過super
調用觸發一個帶有兩個參數( method_id
和destination_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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.