'Order of parameters in ruby method

I have an already existing method in my concern file, which has following number parameters define. For ex

module MyMethods
  def close_open_tasks(param_1, param_2, param_3 = nil)
    p param_1
    p param_2
    p param_3   
  end
end

But I am trying to add one more new optional parameter at the end param_4 in the above method. Lets say I am including this module from an api and calling it from there.

When I call the following

close_open_tasks("test1","test2","test4")

"test4" is getting assigned to param_3 arg. How can I make it assign to param_4? Since both param_3 and param_4 are optional parameters its getting trickier with order.



Solution 1:[1]

If your method has more then two positional arguments or there is no obvious order to the arguments you should define them as keyword arguments.

def close_open_tasks(foo, bar:, baz:) # required
def close_open_tasks(foo, bar: 3, baz: nil) # with defaults

If your method should actually take a list of arguments of any length you can use a splat:

def close_open_tasks(*tasks)
  tasks.map do
    task.close
  end
end
close_open_tasks(task1, task2)

The equivilent for keyword arguments is the double splat:

def close_open_tasks(foo, bar: 3, baz: nil, **opts) 

Which will provide a opts hash containing the additional keyword args.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 max