Asterix with arguments in Ruby

Lets create a method that accepts number of arguments
def my_method(x, *y, **z)
  return x, y, z
end
Concept : x is a regular parameter. *y will take all the parameters passed after the first one and put them in an array. **z will take any parameter given in the format key: value at the end of the method call

See the following examples:

One parameter
my_method(1)
# => [1, [], {}]
More than one parameter
my_method(1, 2, 3, 4)
# => [1, [2, 3, 4], {}]
More than one parameter + hash-style parameters
my_method(1, 2, 3, 4, a: 1, b: 2)
# => [1, [2, 3, 4], {:a=>1, :b=>2}]

Comments

Popular posts from this blog

Inserting and Moving elements inside Ruby Array

Remove duplicates from a JavaScript Array

Sending Binary Data over the Network with Json