ruby convert array into function arguments

后端 未结 2 1129
灰色年华
灰色年华 2020-12-23 13:23

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? F

相关标签:
2条回答
  • 2020-12-23 13:35

    Use this

    a.slice(*b)
    

    It's called the splat operator

    0 讨论(0)
  • 2020-12-23 13:40

    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
    0 讨论(0)
提交回复
热议问题