【问题标题】:Passing an array of arbitrary length as parameters to another method in Ruby将任意长度的数组作为参数传递给 Ruby 中的另一个方法
【发布时间】:2011-06-14 03:29:16
【问题描述】:

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

我一直在为这个而摸不着头脑,但我似乎无法弄清楚。有可能以一种好的方式做到这一点吗?也许我忽略了什么?

【问题讨论】:

标签: ruby xml-rpc


【解决方案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】:

    用您的语言说:

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

    【讨论】:

      【解决方案3】:
      def f (a=nil, b=nil, c=nil)
          [a,b,c]
      end
      
      f(*[1,2]) # => [1, 2, nil]
      

      【讨论】:

      • 不知道为什么有人反对这个;也许缺乏解释?这表明 Ruby splat 运算符允许您在方法调用中将数组转换为单独的参数。
      • 我因缺乏解释而投了反对票,一旦有解释,我很乐意将其删除:)
      • 我觉得不用解释解决方案代码的三个字符。为了解释,问题评论中已经有链接。我应该复制/粘贴/重新发布它们吗?没有。
      猜你喜欢
      • 2018-08-08
      • 1970-01-01
      • 2010-10-24
      • 1970-01-01
      • 2012-09-24
      • 2013-07-01
      • 1970-01-01
      相关资源
      最近更新 更多