ruby convert array into function arguments

杀马特。学长 韩版系。学妹 提交于 2019-12-29 11:30:30

问题


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.


回答1:


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]

Reference:

  • Array to Arguments Conversion



回答2:


Use this

a.slice(*b)

It's called the splat operator



来源:https://stackoverflow.com/questions/14958981/ruby-convert-array-into-function-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!