[英]Passing an array of arbitrary length as parameters to another method in Ruby
我有幾種方法將可變長度數組發送到另一個方法,該方法然后對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 call_rpc(api_call, array_of_values)
client.call(
remote_call,
username,
password,
*array_of_values
)
end
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
def f (a=nil, b=nil, c=nil)
[a,b,c]
end
f(*[1,2]) # => [1, 2, nil]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.