Ruby-ArgumentError:参数数目错误(2代表1)
我有以下课程:Ruby-ArgumentError:参数数目错误(2代表1),ruby,metaprogramming,numeric,method-missing,Ruby,Metaprogramming,Numeric,Method Missing,我有以下课程: 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_curr
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:参数数目错误(2对1)
但是10.dollars.in(:yens)
不会产生错误。知道为什么吗 你写的
def in(destination_currency)
在Ruby中,这意味着您的In
方法只接受一个参数。传递更多参数会导致错误
如果要使其具有可变数量的参数,请使用splat运算符执行以下操作:
def in(*args)
你写的
def in(destination_currency)
在Ruby中,这意味着您的In
方法只接受一个参数。传递更多参数会导致错误
如果要使其具有可变数量的参数,请使用splat运算符执行以下操作:
def in(*args)
您的输入错误:
destination\u curreny
与destination\u curreny
不同。因此,当货币为复数时,您的@@currencies.has\u key?
测试失败,因为它需要查看原始符号(目的地\u curreny
)而不是单数符号(目的地\u curreny
)。这将通过super
调用触发带有两个参数(method\u id
和destination\u currency
)的method\u missing
调用,但您已经声明了method\u missing
以获取一个参数。这就是为什么您忽略了完整引用的错误消息是抱怨方法\u缺失
,而不是中的
修正你的打字错误:
def in(destination_currency)
destination_currency = destination_currency.to_s.gsub(/s$/, '').to_sym
#...
您的输入错误:destination\u curreny
与destination\u curreny
不同。因此,当货币为复数时,您的@@currencies.has\u key?
测试失败,因为它需要查看原始符号(目的地\u curreny
)而不是单数符号(目的地\u curreny
)。这将通过super
调用触发带有两个参数(method\u id
和destination\u currency
)的method\u missing
调用,但您已经声明了method\u missing
以获取一个参数。这就是为什么您忽略了完整引用的错误消息是抱怨方法\u缺失
,而不是中的
修正你的打字错误:
def in(destination_currency)
destination_currency = destination_currency.to_s.gsub(/s$/, '').to_sym
#...
我不明白,我如何传递多个参数?我不明白,我如何传递多个参数?这个问题是离题的,因为它们只允许我们关闭打字/语法相关的问题。这个问题是离题的,因为它们只允许我们关闭打字/语法相关的问题