ruby 将数组转换为函数参数 [英] ruby convert array into function arguments

查看:20
本文介绍了ruby 将数组转换为函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个数组.我希望将数组传递给函数.但是,该函数需要两个参数.有没有办法即时将数组转换为 2 个参数?例如:

Say I have an array. I wish to pass the array to a function. The function, however, expects two arguments. Is there a way to on the fly convert the array into 2 arguments? For example:

a = [0,1,2,3,4]
b = [2,3]
a.slice(b)

在 Ruby 中会产生错误.我需要输入 a.slice(b[0],b[1]) 我正在寻找更优雅的东西,如 a.slice(foo.bar(b))谢谢.

Would yield an error in Ruby. I need to input a.slice(b[0],b[1]) I am looking for something more elegant, as in a.slice(foo.bar(b)) Thanks.

推荐答案

您可以使用 *(或splat")运算符将 Array 转换为参数列表:

You can turn an Array into an argument list with the * (or "splat") operator:

a = [0, 1, 2, 3, 4] # => [0, 1, 2, 3, 4]
b = [2, 3] # => [2, 3]
a.slice(*b) # => [2, 3, 4]

参考:

  • 数组到参数的转换
  • 这篇关于ruby 将数组转换为函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆