假设我有一个数组。我希望将数组传递给函数。但是,该函数需要两个参数。有没有一种方法可以动态地将数组转换成2个参数? 例如:
a = [0,1,2,3,4] b = [2,3] a.slice(b)
将在 Ruby 中产生错误。我需要输入 a.slice(b[0],b[1])我正在寻找更优雅的东西,因为在 a.slice(foo.bar(b)) 谢谢。
a.slice(b[0],b[1])
a.slice(foo.bar(b))
Use this
a.slice(*b)
It's called the splat operator
You can turn an Array into an argument list with the * (or "splat") operator:
Array
*
a = [0, 1, 2, 3, 4] # => [0, 1, 2, 3, 4] b = [2, 3] # => [2, 3] a.slice(*b) # => [2, 3, 4]