ruby将数组转换为函数参数

时间:2021-06-20 23:17:35

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)

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.

会在Ruby中产生错误。我需要输入a。slice(b[0],b[1])我想找一些更优雅的,比如a。slice(b)谢谢。

2 个解决方案

#1


63  

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

可以使用*(或“splat”)操作符将数组转换为参数列表:

irb(main):001:0> a = [0, 1, 2, 3, 4]
=> [0, 1, 2, 3, 4]
irb(main):002:0> b = [2, 3]
=> [2, 3]
irb(main):003:0> a.slice(*b)
=> [2, 3, 4]

Reference:

#2


88  

Use this

使用这个

a.slice(*b)

It's called the splat operator

它叫做splat运算符。

#1


63  

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

可以使用*(或“splat”)操作符将数组转换为参数列表:

irb(main):001:0> a = [0, 1, 2, 3, 4]
=> [0, 1, 2, 3, 4]
irb(main):002:0> b = [2, 3]
=> [2, 3]
irb(main):003:0> a.slice(*b)
=> [2, 3, 4]

Reference:

#2


88  

Use this

使用这个

a.slice(*b)

It's called the splat operator

它叫做splat运算符。