Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a splat from a method in Ruby

Tags:

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]

like image 331
Weston Ganger Avatar asked Feb 25 '26 05:02

Weston Ganger


2 Answers

You cannot return a "splat" from Ruby. But you can return an array and then splat it yourself:

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
like image 67
AmitA Avatar answered Feb 28 '26 15:02

AmitA


The concept that clarifies this for me is that although you can simulate the return of multiple values in Ruby, a method can really return only 1 object, so that simulation bundles up the multiple values in an Array.

The array is returned, and you can then deconstruct it, as you can any array.

def foo
  [1, 2]
end

one, two = foo
like image 24
Keith Bennett Avatar answered Feb 28 '26 14:02

Keith Bennett