질문
일부 타사 앱 A에 대한 클라이언트를 구축하고 있습니다. 여러 매개 변수를 허용하는 많은 메서드가 있으며 그중 일부는 선택 사항입니다. 명명 된 매개 변수를 사용하고 있습니다.
def func1(a: nil, b:, c:, d:, e: nil)
# ...............
call_to_client_internal(a: a, b: b, c: c.....)
end
타사 앱은 nil
인 인수를 허용하지 않습니다. 즉, 각 매개 변수에는 값이 있거나 전달되지 않아야합니다.
func1
에 전달 된 선택적 매개 변수에 값이 있는지 확인하고 해당 매개 변수 만 추가로 call_to_client_internal
에 전달하는지 확인하는 방법이 있습니까? 이 경우 선택 사항은 a
및 e
입니다.
답변1
루비 2.1이라면 할 수있는 방법이 있습니다.
def foo(a: nil, b:nil, c: nil, d: nil, e: nil)
present_args = method(__method__).parameters.select { |arg| binding.local_variable_get(arg[1]) }
...
end
이:
method (: foo) .parameters
로 사용 가능한 인수를 가져옵니다.
binding.local_variable_get (arg [1])
로 값을 가져옵니다.
- 필요에 따라 사용할 것을 선택하고
present_args
에 저장합니다 (더 나은 이름을 생각할 수 있습니다.
따라서 귀하의 경우에는 reduce
를 사용하도록 확장하겠습니다.
def func1(a: nil, b:nil, c: nil, d: nil, e: nil)
present_args_hash = method(__method__).parameters.reduce({}) do |hash, (_, arg)|
next hash unless (val = binding.local_variable_get(arg))
hash.merge(arg => val)
end
call_to_client_internal(present_args_hash)
end
이것은이 작업을 수행하는 매우 간단한 방법으로 보입니다. 존재하는 키워드 인수의 해시를 작성하여 클라이언트로 보냅니다.
어떻게 타는 지 알려주세요! 질문이 있으시면 기꺼이 도와 드리겠습니다.
답변2
나는 이것이 제안에 따라 더 간단한 방법이라고 믿습니다.
# ** means func1 accepts only named parameters
# options is a hash of optional parameters
# .compact removes all nil values from hash
def func1(b:, c:, d:, **options)
# if you want, you can leave only those option params you want:
options = options.slice(:a, :e)
# For Ruby 2.4 and above
options = options.merge(b: b, c: c, d: d).compact
# For Ruby 2.3 and below
options = options.merge(b: b, c: c, d: d).reject { |_, v| v.nil? }
call_to_client_internal(options)
end
답변3
나에게 안전한 해결책으로 보이는 새 해시
를 만드는 것이 좋습니다. 다음과 같이 할 수 있습니다 (a가 초기 해시라고 가정).
b = {}
a.each{|k,v| b[k] = v if !v.nil?}
그런 다음 b
를 입력 해시로 함수에 전달합니다.
답변4
func1
에 전달하기 전에 키를 삭제할 수 있습니다.뭔가
hash = {a: nil, b: b, c: c, d: d, e: nil}.delete_if { |k, v| v.nil? }
func1(hash)
또한 함수는 다음과 같아야합니다.
def func1(a: nil, b: nil, c: nil, d: nil, e: nil)
#
end
또 다른 방법은 hash
변수를 모든 곳에 전달하는 것입니다. 이렇게하면 동일한 해시 변수를 call_to_client ..
메소드에 추가로 전달할 수 있습니다.
hash = {a: nil, b: b, c: c, d: d, e: nil}.delete_if { |k, v| v.nil? }
func1(hash)
def func1(hash)
# use hash[:a] and so on
call_to_client_internal(hash)
end
출처 : https://stackoverflow.com/questions/48560049/a-wise-way-to-select-only-those-optional-named-parameters-that-have-a-value