Ronan Lopes Ronan Lopes - 1 month ago 16
Ruby Question

Ruby - Optional argument wrong match

I have a ruby function with the following signature:

def botao_adicionar(model, prefix = "/#{model.name.tableize}", callback = nil)


and I want to make it a call without pass the
prefix
argument, so it takes the default from function that I defined above. So I call it this way:

botao_adicionar(model=ArrendamentoContrato, callback="bind_unidades_consumidoras()")


And it associates the
callback
value to
prefix
variable. I believe it's matching by the order of arguments, but I explicitly called the name of the argument in the function call... that shouldn't work? Thanks!

Answer

All your arguments are positional. Meaning that you can't assign them by name.

It seems that you want to use keyword arguments. The correct syntax for them is this:

def botao_adicionar(model, prefix: "/#{model.name.tableize}", callback: nil)

And then

botao_adicionar(ArrendamentoContrato, callback: "bind_unidades_consumidoras()")