开发者

Passing an array of arbitrary length as parameters to another method in Ruby

I have several methods that sends a variable length array to another method which then makes an XML::RPC call to an API.

Now, how do I pass these into XML::RPC when they are of an undefined length?

def call_rp开发者_运维知识库c(api_call, array_of_values)
  client.call(
    remote_call, 
    username, 
    password, 
    value_in_array_of_values_1,
    ...,
    value_in_array_of_values_n
  )
end

I have been scratching my head for this one and I can't seem to figure it out. Is it possible to do this in a nice way? Maybe I have overlooked something?


Spoken in your language:

def call_rpc(api_call, array_of_values)
  client.call(
    remote_call, 
    username, 
    password, 
    *array_of_values
  )
end


The Ruby splat/collect operator * may help you. It works by converting arrays to comma seperated expressions and vice versa.

Collecting parameters into an array

*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"]

Splatting an array into parameters

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]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜