将任意长度的数组作为参数传递给Ruby中的另一个方法

将任意长度的数组作为参数传递给Ruby中的另一个方法,ruby,xml-rpc,Ruby,Xml Rpc,我有几个方法将可变长度数组发送给另一个方法,然后该方法对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

我有几个方法将可变长度数组发送给另一个方法,然后该方法对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

我一直在为这件事挠头,但我似乎弄不明白。有没有可能用一种好的方式来做这件事?也许我忽略了什么?

用你的语言说:

def f (a=nil, b=nil, c=nil)
    [a,b,c]
end

f(*[1,2]) # => [1, 2, nil]
def call_rpc(api_call, array_of_values)
  client.call(
    remote_call, 
    username, 
    password, 
    *array_of_values
  )
end

Ruby splat/collect操作符
*
可能会帮助您。它的工作原理是将数组转换为逗号分隔的表达式,反之亦然

将参数收集到数组中 将数组拆分为参数
请参阅--note Happy编码。谢谢,这正是我一直在看的内容,但是sprintf的示例已经清楚地说明了这一点!不知道为什么有人否决了这一点;也许缺乏解释?这表明Ruby splat运算符允许您在方法调用中将数组转换为单个参数。我对缺少解释投了反对票,一旦有解释,我会很乐意删除它:)我认为我不必解释解决方案代码的三个字符。对于解释,已经有了相关评论的链接。我需要复制/粘贴/重新发布它们吗?不
*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