여러 매개 변수를 전달하는 루비 전송 메소드
에 의해 객체를 생성하고 메소드를 동적으로 호출하려고 시도
Object.const_get(class_name).new.send(method_name,parameters_array)
때 잘 작동합니다
Object.const_get(RandomClass).new.send(i_take_arguments,[10.0])
그러나 2에 대해 잘못된 수의 인수 1을 던졌습니다.
Object.const_get(RandomClass).new.send(i_take_multiple_arguments,[25.0,26.0])
정의 된 랜덤 클래스는
class RandomClass
def i_am_method_one
puts "I am method 1"
end
def i_take_arguments(a)
puts "the argument passed is #{a}"
end
def i_take_multiple_arguments(b,c)
puts "the arguments passed are #{b} and #{c}"
end
end
누군가가 루비 메소드에 다중 매개 변수를 동적으로 보내는 방법을 알려줄 수 있습니까?
send("i_take_multiple_arguments", *[25.0,26.0]) #Where star is the "splat" operator
또는
send(:i_take_multiple_arguments, 25.0, 26.0)
대신 send
동의어로 호출 할 수 있습니다 __send__
.
r = RandomClass.new
r.__send__(:i_take_multiple_arguments, 'a_param', 'b_param')
그런데 * 쉼표로 구분 된 해시를 다음과 같이 구분하여 해시를 전달할 수 있습니다.
imaginary_object.__send__(:find, :city => "city100")
또는 새로운 해시 구문 :
imaginary_object.__send__(:find, city: "city100", loc: [-76, 39])
Black에 따르면 __send__
네임 스페이스가 더 안전합니다.
“전송은 광범위한 개념입니다. 전자 메일, 데이터가 I / O 소켓으로 전송됩니다. 프로그램이 Ruby의 내장 send 메소드와 충돌하는 send 메소드를 정의하는 것은 드문 일이 아닙니다. 따라서 Ruby는 send :를 호출하는 다른 방법을 제공합니다
__send__
. 관례 적으로 아무도 그 이름으로 메소드를 작성하지 않으므로 내장 Ruby 버전은 항상 사용 가능하며 새로 작성된 메소드와 충돌하지 않습니다. 이상하게 보이지만 method-name 충돌의 관점에서 일반 전송 버전보다 안전합니다.”
블랙은 __send__
에서 호출을 줄 바꿈하기도합니다 if respond_to?(method_name)
.
if r.respond_to?(method_name)
puts r.__send__(method_name)
else
puts "#{r.to_s} doesn't respond to #{method_name}"
end
Ref : Black, David A. 잘 짜여진 Rubyist. 매닝, 2009. P.171.
*에 대한 해시 구문을 __send__
찾으러 왔으므로 다른 Google 직원에게 유용 할 수 있습니다. ;)
참고 URL : https://stackoverflow.com/questions/13795627/ruby-send-method-passing-multiple-parameters
'Programing' 카테고리의 다른 글
브라우저가 팝업을 차단하고 있는지 어떻게 알 수 있습니까? (0) | 2020.07.17 |
---|---|
git에서 체크 아웃을 취소하려면 어떻게합니까? (0) | 2020.07.17 |
Atom 편집기에서 RegEx 구성 요소 검색 및 바꾸기 (0) | 2020.07.17 |
적합한 신청 기록이 없습니다. (0) | 2020.07.17 |
WHERE 절의 참조 별명 (SELECT에서 계산 됨) (0) | 2020.07.17 |