Ruby-ArgumentError:잘못된 인수의 수(2 대 1)
-
11-12-2019 - |
문제
나는 다음과 같은 클래스를 덮어쓰기:
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)
을 수 없다면 오류가 있습니다.이유가 무엇입니까?
해결책
귀하의루 오타: destination_curreny
동일하지 않은 destination_currency
.그래서 때는 통화가 복수 h @@currencies.has_key?
테스트 실패하기 때문에 보면 원래의 상징(destination_currency
)보다는 오히려드러지게 하는 기호(destination_curreny
).을 트리거 method_missing
전화를 가진 두 개의 인수(method_id
고 destination_currency
다)이 super
전화지만 당신을 선언 method_missing
을 한다.하는 이유는 오류 메시지를 무시하는 완전히 견적에 대해 불평 method_missing
보 in
.
오타 수정:
def in(destination_currency)
destination_currency = destination_currency.to_s.gsub(/s$/, '').to_sym
#...
다른 팁
를 썼습니다
def in(destination_currency)
.
루비에서는 in
메서드가 정확히 하나의 인수를 취함을 의미합니다.더 많은 인수를 전달하면 오류가 발생합니다.
가변 수의 인수가있는 경우 splat 연산자와 같은 다음을 수행하도록하려면 다음을 수행하십시오.
def in(*args)
. 제휴하지 않습니다 StackOverflow