Home > Net >  Order of parameters in ruby method
Order of parameters in ruby method

Time:02-04

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.

CodePudding user response:

You can use keywords arguments

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

and call it like this

close_open_tasks(param_1: "test1", param_2: "test2", param_4: "test4")

CodePudding user response:

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.

  •  Tags:  
  • Related