WestonGanger WestonGanger - 7 months ago 19
Ruby Question

How to return a splat from a method in Ruby

I wanted to create a method for array's to get a splat of the array in return. Is this possible to do in Ruby?

For example here's my current code:

Array.module_eval do
def to_args
return *self
end
end


I expect
[1,2,3].to_args
to return
1,2,3
but it ends up returning
[1,2,3]

Answer

You cannot return a "splat" from Ruby. But if you return an array, Ruby will "splat" it for you:

def args
  [1, 2, 3]
end
x, y, z = args 
# x == 1
# y == 2
# z == 3

x, *y = args
# x == 1
# y == [2, 3]

Of course, this works on any array, so really there is no need for monkey patching a to_args method into Array - it's all about how the calling concern is using the splat operator:

arr = [1, 2, 3]
x, y, z = arr
x, *y = arr
*x, y = arr

Same mechanism works with block arguments:

arr = [1, 2, 3]
arr.tap {|x, *y| y == [2, 3]} 

Even more advanced usage:

arr = [1, [2, 3]]
x, (y, z) = arr