我有几种方法可以将一个可变长度数组发送到另一个方法,然后该方法对API进行XML :: RPC调用。
现在,当它们是未定义的长度时,如何将它们传递给XML :: RPC?
def call_rpc(api_call, array_of_values)
client.call(
remote_call,
username,
password,
value_in_array_of_values_1,
...,
value_in_array_of_values_n
)
end
我一直在摸不着头脑,我似乎无法弄明白。有可能以一种很好的方式做到这一点吗?也许我忽略了什么?
答案 0 :(得分:2)
用您的语言说:
def call_rpc(api_call, array_of_values)
client.call(
remote_call,
username,
password,
*array_of_values
)
end
答案 1 :(得分:1)
Ruby splat / collect运算符*
可能会对您有所帮助。它的工作原理是将数组转换为逗号分隔的表达式,反之亦然。
*collected = 1, 3, 5, 7
puts collected
# => [1,3,5,7]
def collect_example(a_param, another_param, *all_others)
puts all_others
end
collect_example("a","b","c","d","e")
# => ["c","d","e"]
an_array = [2,4,6,8]
first, second, third, fourth = *an_array
puts second # => 4
def splat_example(a, b, c)
puts "#{a} is a #{b} #{c}"
end
param_array = ["Mango","sweet","fruit"]
splat_example(*param_array)
# => Mango is a sweet fruit
答案 2 :(得分:0)
def f (a=nil, b=nil, c=nil)
[a,b,c]
end
f(*[1,2]) # => [1, 2, nil]